原标题:如何在实际对象调用之前动态地将属性包含在变量中
通用问题
如何以正确$target
的方式创建var_dumped
?
$type = 'lib';
$target = 'test->test2';
var_dump($GLOBALS[$this->context]->$type->test->test2);//returns object(test\test2)#15 (0) { }
var_dump($GLOBALS[$this->context]->$type->{$target}); //returns NULL ( Undefined property: stdClass::$test->test2 )
更多示例
这个(下面)就像一个魅力
$target = 'test';
$type = new \stdClass();
$type->test = new \stdClass();
$type->test->test2 = 5;
var_dump($type->$target); // Returns object(stdClass)#24 (1) { ["test2"]=> int(5) }
这(下面)没有:
$target = 'test->test2';
$type = new \stdClass();
$type->test = new \stdClass();
$type->test->test2 = 5;
var_dump($type->$target);// Returns NULL (Notice: Undefined property: stdClass::$test->test2)
真实案例:
我想取消设置$GLOBALS[$this->context]->$type->test->test2
我的第一个:
public function unSys($type, $thing) {
//$type = 'lib';
//$thing = 'test/test2';
$parts = explode('/',$thing);
$final = implode('->',$parts);
unset($GLOBALS[$this->context]->$type->{$final});
}
之后我尝试过:
...
$parts = explode('/',$thing);
$target = $GLOBALS[$this->context]->$type;
foreach ($parts as $value) {
$target = $target->$value;
}
unset($target);
var_dump($GLOBALS[$this->context]->$type->test->test2);//still exist
...
我也尝试过没有运气的参考传递:
...
$target = &$GLOBALS[$this->context]->$type;
...
答案 0 :(得分:1)
纪尧姆
我认为您希望使用表示嵌套对象链的属性名称数组来删除最后一个嵌套对象属性。
查看此代码是否有意义并解决您的问题。
>>> from operator import itemgetter
>>> sorted(seq, key = itemgetter(1), reverse = True)
<?PHP
$GLOBALS['tmp'] = (object)array( 'lib' => (object)array( 'test' => (object)array( 'test2' => (object)array()) ) );
var_dump( $GLOBALS['tmp'] );
$context = 'tmp';
$type = 'lib';
$thing = 'test/test2';
$parts = explode('/',$thing);
$target = $GLOBALS[$context]->$type;
var_dump( $target );
var_dump( $parts );
$itemToUnset = array_pop( $parts );
foreach ($parts as &$value) {
$target =& $target->$value;
}
unset( $target->{$itemToUnset} );
var_dump( $GLOBALS['tmp'] );
// test 2 is not set
var_dump( $GLOBALS['tmp']->lib->test->test2 );