在PHP的匿名函数中访问对象的私有/受保护的属性 [英] Accessing private/protected properties of an object in anonymous function in PHP

查看:171
本文介绍了在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);
    }
}

这篇关于在PHP的匿名函数中访问对象的私有/受保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆