Accessing private/protected properties of an object in anonymous function in PHP

后端 未结 3 1265
深忆病人
深忆病人 2021-01-13 11:36

I\'m trying to dump elements of an object\'s private property through an anonymous function - of course I could achieve this in any number of other ways, but this highlights

3条回答
  •  感情败类
    2021-01-13 12:29

    You can hack around the limitation by creating a wrapper that utilizes Reflection to allow you to access all properties and methods. You can use it like this then:

    $self = new FullAccessWrapper($this);
    function () use ($self) { /* ... */ }
    

    Here a sample implementation of the wrapper, taken from here:

    class FullAccessWrapper
    {
        protected $_self;
        protected $_refl;
    
        public function __construct($self)
        {
            $this->_self = $self;
            $this->_refl = new ReflectionObject($self);
        }
    
        public function __call($method, $args)
        {
            $mrefl = $this->_refl->getMethod($method);
            $mrefl->setAccessible(true);
            return $mrefl->invokeArgs($this->_self, $args);
        }
    
        public function __set($name, $value)
        {
            $prefl = $this->_refl->getProperty($name);
            $prefl->setAccessible(true);
            $prefl->setValue($this->_self, $value);
        }
    
        public function __get($name)
        {
            $prefl = $this->_refl->getProperty($name);
            $prefl->setAccessible(true);
            return $prefl->getValue($this->_self);
        }
    
        public function __isset($name)
        {
            $value = $this->__get($name);
            return isset($value);
        }
    }
    

    Obviously the above implementation doesn't cover all aspects (e.g. it can't use magic properties and methods).

提交回复
热议问题