在PHP的匿名函数中访问对象的私有/受保护的属性

在PHP的匿名函数中访问对象的私有/受保护的属性

问题描述:

我正在尝试通过匿名函数转储对象的私有属性的元素-当然,我可以通过许多其他方式来实现此目的,但这凸显了我无法解决的PHP难题,缺少$ foo = $ this并使用$ foo-但是那不会给我私人的东西,所以...建议?

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 a PHP conundrum I can't solve off the top of my head, short of $foo = $this and using $foo - but THAT won't give me the private stuff, so... suggestions ?

示例代码:

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();

我相信绝对没有办法直接完成您的建议.

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

但是,您可以通过以下方式解决此问题:将匿名方法设为类方法(这不是您所需要的,但这可能是一个实用的解决方案),或者将您需要的所有内容明确地从$this中取出并传递给将值提取到函数中:

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);
    }
}