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

后端 未结 3 1287
深忆病人
深忆病人 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:20

    I believe there is absolutely no way to do directly what you propose.

    However, you can work around it either by making the anonymous method a class method (this is not what you asked for, but it could be a practical solution) or pulling everything you need out of $this explicitly and passing the extracted values into 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);
        }
    }
    

提交回复
热议问题