PHP Access通过数组中的字符串访问嵌套对象属性 [英] PHP Access nested object property via strings in array

查看:354
本文介绍了PHP Access通过数组中的字符串访问嵌套对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个对象$ obj.该对象具有如下属性:

Let's say we have an object $obj. This object has a property which is as follows:

$obj->p1->p2->p3 = 'foo';

现在,我在数组中获得了嵌套的属性结构:

Now I get the nested property structure in an array:

$arr = array( 'p1', 'p2', 'p3' );

当前,我使用以下函数来相应地访问属性:

Currently I use the following function to access the property accordingly:

function getProperty( $obj, $property ) {
foreach( $property as $p ) {
  $obj = $obj->{$p};
 }
 return $obj;
}

$value = getProperty( $obj, $arr); // = 'foo'

是否有一种更聪明的方法(不,'eval'不是一种选择!;))?

Is there a smarter way to do that (no, 'eval' is not an option! ;) )?

推荐答案

如果您希望将其制作成一行或更漂亮,可以尝试以下方法:

If you want to make it in one line or a bit prettier, you can try this:

echo json_decode(json_encode($obj), true)['p1']['p2']['p3']; // PHP 5.4

或对于PHP 5.3:

or for PHP 5.3:

$arr = json_decode(json_encode($obj), true);
echo $arr['p1']['p2']['p3'];

您要实现的目标吗?

这篇关于PHP Access通过数组中的字符串访问嵌套对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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