如何在php中访问名为变量(点表示法)的深层对象属性? [英] How can I access a deep object property named as a variable (dot notation) in php?

查看:52
本文介绍了如何在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:

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中访问名为变量(点表示法)的深层对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆