英文:
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, "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");
?>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论