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

查看:26
本文介绍了在 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天全站免登陆