Access to private / protected object properties in anonymous function in PHP

I am trying to dump the private property of an object through an anonymous function - of course, I could achieve this in any other way, but this emphasizes the PHP riddle that I cannot solve from head to toe, except for $ foo = $ this and using $ foo - but it won’t give me personal stuff, so ... suggestions?

Code example:

class MyClass { private $payload = Array( 'a' => 'A element', 'b' => 'B element'); static $csvOrder = Array('b','a'); public function toCSV(){ $values = array_map( function($name) use ($this) { return $this->payload[$name]; }, self::$csvOrder ); return implode(',',$values); } } $mc = new MyClass(); print $mc->toCSV(); 
+5
oop php anonymous-function
Jun 17 2018-11-17T00:
source share
3 answers

I believe that it is absolutely impossible to directly do what you offer.

However, you can work around this by making the anonymous method a class (this is not what you asked for, but it can be a practical solution) or pull everything you need from $this explicitly and pass the extracted values ​​to the function:

 class MyClass { private $payload = Array( 'a' => 'A element', 'b' => 'B element'); static $csvOrder = Array('b','a'); public function toCSV(){ $payload = $this->payload; $values = array_map( function($name) use ($payload) { return $payload[$name]; }, self::$csvOrder ); return implode(',',$values); } } 
+3
Jun 17 '11 at 13:52
source share

You can crack the constraint by creating a wrapper that uses Reflection so that you can access all the properties and methods. You can use it like this:

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

Here's a sample shell implementation, 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 does not cover all aspects (for example, it cannot use magic properties and methods).

+3
Jun 17 2018-11-11T00:
source share

As you said yourself, it is private and therefore accessible.

You can:

  • Pass $ this-> payload as a parameter to an anonymous function.
  • Create a method in the class and use it instead.
+1
Jun 17 2018-11-17T00:
source share



All Articles