Parent Object in php

后端 未结 6 1615
抹茶落季
抹茶落季 2020-12-15 08:57

is there a way to traverse an object to get the parent object data? With \"parent object\" I don\'t mean the parent class, but literally object. Here an example, in a javasc

6条回答
  •  [愿得一人]
    2020-12-15 09:44

    Maybe it can be useful in some case: it doesn't bring parent object to ChildClass very early in constructor, but a one step later. It plays with ability to intercept non-existing method:

    class ParentClass
    {
        const CHILD_PROPERTY_NAME = 'child';
        public $data = 'Some data';
    
        public function
        __set($property_name, $property_value)
        {
            if ($property_name == self::CHILD_PROPERTY_NAME)
            {
                $property_value->set_parent_object($this);
            }
        }
    }
    
    
    class ChildClass
    {
        private $parent_object = null;
    
        public function
        set_parent_object($object)
        {
            $this->parent_object = $object;
            echo $this->parent_object->data;
        }
    
    }
    
    
    $p = new ParentClass();
    $p->child = new ChildClass();
    

    This will output Some data

提交回复
热议问题