使用 object 属性 名称数组删除深度嵌套的 object 属性

Removing a deeply nested object property using an array of object property names

原标题:如何在实际object调用

之前动态地将属性包含在变量中

一般问题

如何创建 $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;
...

纪尧姆,

我认为您想要使用代表嵌套对象链的 属性 个名称的数组来删除最后一个嵌套对象 属性。

看看这段代码是否有意义并能解决您的问题。

<?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 );

输出如下所示:

object(stdClass)[4]
public 'lib' => 
    object(stdClass)[3]
        public 'test' => 
          object(stdClass)[2]
            public 'test2' => 
              object(stdClass)[1]
                ...
object(stdClass)[3]
public 'test' => 
    object(stdClass)[2]
        public 'test2' => 
        object(stdClass)[1]

array (size=2)
0 => string 'test' (length=4)
1 => string 'test2' (length=5)

object(stdClass)[4]
public 'lib' => 
    object(stdClass)[3]
        public 'test' => &
        object(stdClass)[2]

Notice: Undefined property: stdClass::$test2