我可以通过编程方式创建一个PHP对象引用链吗? [英] Can I create a chain of PHP object references programmatically?
本文介绍了我可以通过编程方式创建一个PHP对象引用链吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我知道如何获取一组任意键,并使用它们来像这样创建对象引用...
For example, I know how to take an arbitrary set of keys and use them to make object references like this...
$arr = array("A", "B", "C");
foreach($arr as $key):
echo $obj->{$key} . "\n";
endforeach;
// prints $obj->A, $obj->B and $obj->C
但是,如果我要访问的对象中有多个引用级别,该怎么办?是否可以即时添加更多箭头运算符?
But what if I have multiple levels of references within an object that I want to access? Is it possible to add more arrow operators on the fly?
$arr = array(array("A", "B"),
array("C", "D", "E"),
array("F"));
foreach($arr as $key_arr):
// ???
endforeach;
// prints $obj->A->B, $obj->C->D->E, $obj->F
推荐答案
在回显之前,您必须遍历名称并在最后一个对象上保留引用.
You have to loop over the names and maintain a reference on the last object before to echo.
foreach($arr as $key_arr) {
$ref = $obj ;
foreach ($key_arr as $item) {
$ref = $ref->{$item} ; // $obj->A, then $obj->A->B
}
echo $ref ;
}
-
$ref = $obj
- 然后
$ref = $ref->A
- 然后
$ref = $ref->B
这样$ref->A->B
- 依此类推...
- 然后回显上一个引用
$ref = $obj
- Then
$ref = $ref->A
- Then
$ref = $ref->B
so$ref->A->B
- And so on...
- Then echo the last reference
这篇关于我可以通过编程方式创建一个PHP对象引用链吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文