How can I access a deep object property named as a variable (dot notation) in php?

前端 未结 5 1506
醉梦人生
醉梦人生 2020-11-27 08:05

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.

Let\'s say I

5条回答
  •  悲哀的现实
    2020-11-27 08:35

    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.

提交回复
热议问题