How can I access a deep object property named as a variable (dot notation) in php?(如何访问在 php 中命名为变量(点表示法)的深层对象属性?)
问题描述
有很多与此类似的问题,但这里略有不同,因为它是关于深度对象属性访问的,而不仅仅是一层深度.
There are many questions similar to this, however this is slightly different since it's about deep object property access, not just one level of depth.
假设我有一个包含字符串 foo.bar
的变量.
Let's say I have a variable containing the string foo.bar
.
$user = new User();
$user->foo = new Foo();
$user->foo->bar = "Hello World";
$variable = "foo.bar"
我想通过使用 $variable
来回显 $user->foo->bar
:
I would like to echo $user->foo->bar
by making use of $variable
:
echo $user->foo->bar
这是我迄今为止尝试过但没有成功的方法(它说 NULL):
This is what I have tried so far but with no success (it says NULL):
$value = str_replace(".", "->", $value);
echo $user->{$value};
推荐答案
使用可变属性符号($o->$p减少对象路径非常容易代码>):
It is very easy to reduce the object path using variable property notation ($o->$p
):
$path = 'foo.bar';
echo array_reduce(explode('.', $path), function ($o, $p) { return $o->$p; }, $user);
这很容易变成一个小的辅助函数.
This could easily be turned into a small helper function.
这篇关于如何访问在 php 中命名为变量(点表示法)的深层对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何访问在 php 中命名为变量(点表示法)的深层对象属性?


基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01