How to use __get() to return null in multilevel object property accessing?

前端 未结 3 1563
北恋
北恋 2021-01-21 02:31

How can I use __get() to return null in multilevel object property accessing the case like this below?

For instance, this is my classes,

class property          


        
3条回答
  •  天涯浪人
    2021-01-21 03:11

    Yes, I know it's been 4 years ago, but I had a similar problem this week, and while I trying to solve it, I found this thread. So, here is my solution:

    class NoneWrapper
    {
        private $data;
    
        public function __construct($object)
        {
            $this->data = $object;
        }
    
        public function __get(string $name)
        {
            return property_exists($this->data, $name)
                ? new NoneWrapper($this->data->$name)
                : new None;
        }
    
        public function __call($name, $arguments)
        {
            if (is_object($this->data)) {
                return (property_exists($this->data, $name))
                ? $this->data->$name
                : null;
            } else {
                return null;
            }
        }
    
        public function __invoke()
        {
            return $this->data;
        }
    }
    
    class None
    {
        public function __get(string $name) {
            return new None;
        }
    
        public function __call($name, $arguments)
        {
            return null;
        }
    
        public function __invoke()
        {
            return null;      
        }
    }
    
    $object = new NoneWrapper(
        json_decode(
            json_encode([
                'foo' => [
                    'bar' => [
                        'first' => 1,
                        'second' => 2,
                        'third' => 3,
                        'fourth' => 4,
                    ],
                ]
            ])
        )
    );
    
    var_dump($object->foo->bar->baz()); // null
    var_dump($object->foo->bar->third()); // 3
    

提交回复
热议问题