Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

php - 如何使用字符串变量访问对象的子级?(How to access children of an object using a string variable?)

I have a function where I want to work with an object.

(我有一个要在其中使用对象的函数。)

I would like to specify a child of that object with a string.

(我想用字符串指定该对象的子代。)

I know the child is possible with $x , but is it possible to go deeper with something like $y , too?

(我知道孩子可以用$x ,但是也可以像$y一样做得更深吗?)

<?php
    $obj = new stdClass;
    $obj->token = new stdClass;
    $obj->token->id = 123;

    $x = 'created'; 
    $obj->token->{$x} = 456;    

    $y = 'token->updated';
    $obj->{$y} = 789;   

    print_r($obj);
?>

Obviously, that doesn't work, but I would like to get

(显然,这行不通,但我想得到)

stdClass Object
(
    [token] => stdClass Object
        (
            [id] => 123
            [created] => 456
            [updated] => 789
        )

)

Thank you!

(谢谢!)

  ask by Josef Habr translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It would not work if you include the arrow.

(如果包含箭头,它将不起作用。)

This on the other hand works:

(另一方面,这可以工作:)

$obj->{$x}->{$y} = 111;

If the arrow is something you have to have in the variable you can do some trickery like this:

(如果变量中必须包含箭头,则可以执行以下操作:)

$deepVar = 'token->update';
$a = &$obj;
foreach (explode('->', $deepVar) as $varName) {
    $a = &$a->{$varName};
}
$a = 111;
unset($a);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...