简体   繁体   English

如何在PHP中从对象属性中获取值并将路径存储在变量中?

[英]How can I get in PHP the value out of an object attribute with the path stored in a variable?

For example, I have the following: $ValuePath = "object->data->user_nicename"; 例如,我具有以下内容: $ValuePath = "object->data->user_nicename";

And I need to print not the value of the $ValuePath but the value of the $variable->data->user_nicename that is part of a larger call .. as I have the following situation: 而且我不需要打印$ ValuePath的值,而是打印$variable->data->user_nicename的值,这是较大调用..的一部分,因为我有以下情况:

echo $objects->$ValuePath->details;

and is not working .. I'm getting the error Class cannot be converted to string or something when I try it like that. 并且不起作用..我收到这样的错误,当我尝试这样时,类无法转换为字符串或其他东西。

PHP pseudo-code: PHP伪代码:

function get_by_path($object, $path)
{
    $o = $object;
    $parts = explode('->', $path);
    // if you want to  remove the first dummy object-> reference
    array_shift($parts);
    $l = count($parts);
    while ($l)
    {
        $p = array_shift($parts); $l--;
        if ( isset($o->{$p}) ) $o = $o->{$p};
        else {$o = null; break;}
    }
    return $o;
}

Use like this: 像这样使用:

$value = get_by_path($obj, "object->data->user_nicename"); 
// $value = $obj->data->user_nicename;

Check also PHP ArrayAccess Interface which enables to access objects as arrays dynamicaly 另请检查PHP ArrayAccess接口 ,该接口可动态访问作为数组的对象

NO you cannot do that. 不,你不能那样做。

From your declaration $ValuePath is a variable which holds a plain string ('object->data->user_nicename') this string is not an object. 在声明中, $ValuePath是一个变量,该变量包含一个纯字符串(“ object-> data-> user_nicename”),该字符串不是对象。
Where as, $objects->object->data->user_nicename->details is a object. 其中, $objects->object->data->user_nicename->details是一个对象。

so $objects->object->data->user_nicename->details is not same as $objects->$ValuePath->details 所以$objects->object->data->user_nicename->details$objects->$ValuePath->details

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM