将对象路径传递给函数

huangapple go评论83阅读模式
英文:

Php pass object path to function

问题

这可能很简单。给定以下对象和函数:

$object = new stdClass();
$object->a = 'Here we go';
$object->b->first = "again";
$object->b->second = "and again";

function get_item($object, $item){
    print_r($object->{$item});
}

get_item($object, "a"); // works
get_item($object, "b->first"); // NOTICE Undefined property: stdClass::$b

虽然将单个属性传递给函数可以正常工作,但传递类似 b->first 的路径会失败。有人可以指导我如何解决这个问题吗?

英文:

this might be super easy. Given is the following object and function:

$object = new stdClass();
$object->a = 'Here we go';
$object->b->first = "again";
$object->b->second = "and again";

function get_item($object, $item){
	print_r($object->{$item});
}

get_item($object, "a"); // works
get_item($object, "b->first"); // NOTICE Undefined property: stdClass::$b

While it's working to pass a single property to a function, passing a path like b->first fails. Can someone bring me on track how to solve this?

答案1

得分: 4

你不能直接这样做,但可以逐级进行,所以在函数中使用explode()将其拆分为每个级别,然后逐个应用它...

function get_item($object, $item){
    $output = $object;
    foreach ( explode("->", $item) as $level )  {
        $output = $output->{$level};
    }
    print_r($output);
}
英文:

You cannot do it directly, but you can do it level by level, so in the function use explode() to split it into each level and apply it one at a time...

function get_item($object, $item){
    $output = $object;
    foreach ( explode("->", $item) as $level )  {
        $output = $output->{$level};
    }
    print_r($output);
}

答案2

得分: 1

You can also do this way, instead of get_item($object, "b->first"); use get_item($object->b, "first");

<?php
$object = new stdClass();

$object->b = new stdClass();
$object->b->first = "again";
$object->b->second = "and again";

function get_item($object, $item){
    print_r($object->{$item});
}

get_item($object->b, "first");
?>
英文:

You can also do this way, instead of get_item($object, &quot;b-&gt;first&quot;); use get_item($object-&gt;b, &quot;first&quot;);

&lt;?php
$object = new stdClass();

$object-&gt;b = new stdClass();
$object-&gt;b-&gt;first = &quot;again&quot;;
$object-&gt;b-&gt;second = &quot;and again&quot;;

function get_item($object, $item){
    print_r($object-&gt;{$item});
}


get_item($object-&gt;b, &quot;first&quot;);
?&gt;

huangapple
  • 本文由 发表于 2020年1月6日 20:11:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定