php – 根据类定义一个闭包作为方法

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 根据类定义一个闭包作为方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图玩PHP5.3和关闭.

在这里看到(清单7中的对象关闭http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html)可以在回调函数中使用$this,但不是.所以我试图给$$作为使用变量:

$self = $this;
$foo = function() use($self) { //do something wITh $self }

所以要用同样的例子:

class Dog
{
PRivate $_name;
protected $_color;

public function __construct($name,$color)
{
     $this->_name = $name;
     $this->_color = $color;
}
public function greet($greeting)
{
     $self = $this;
     return function() use ($greeting,$self) {
         echo "$greeting,I am a {$self->_color} dog named {$self->_name}.";
     };
}
}

$dog = new Dog("Rover","red");
$dog->greet("Hello");

Output:
Hello,I am a red dog named Rover.

首先这个例子不打印字符串但是返回函数,但这不是我的问题.

其次,我无法访问私有或受保护,因为回调函数一个全局函数,而不是在上下文中从Dog对象.不是我的问题与以下相同:

function greet($greeting,$object) {
    echo "$greeting,I am a {$self->_color} dog named {$self->_name}.";
}

而且我要 :

public function greet($greeting) {
    echo "$greeting,I am a {$self->_color} dog named {$self->_name}.";
}

哪个来自狗而不是全球.

嗯,你不能使用$this的全部原因是因为闭包是后台的对象(Closure类).

这有两种方法.首先,添加__invoke方法(如果调用$obj(),调用)..

class Dog {

    public function __invoke($method) {
        $args = func_get_args();
        array_shift($args); //get rid of the method name
        if (is_callable(array($this,$method))) {
            return call_user_func_array(array($this,$method),$args);
        } else {
            throw new BadMethodCallException('UnkNown method: '.$method);
        }
    }

    public function greet($greeting) {
        $self = $this;
        return function() use ($greeting,$self) {
            $self('do_greet',$greeting);
        };
    }

    protected function do_greet($greeting) {
        echo "$greeting,I am a {$this->_color} dog named {$this->_name}.";
    }
}

如果您想要修改主机对象时关闭不变,您可以将返回函数改为

public function greet($greeting) {
    $self = (clone) $this;
    return function() use ($greeting,$self) {
        $self('do_greet',$greeting);
    };
}

一个选择是提供一个通用的getter:

class Dog {

    public function __get($name) {
        return isset($this->$name) ? $this->$name : null;
    }

}

有关更多信息,请参阅:http://www.php.net/manual/en/language.oop5.magic.php

脚本宝典总结

以上是脚本宝典为你收集整理的php – 根据类定义一个闭包作为方法全部内容,希望文章能够帮你解决php – 根据类定义一个闭包作为方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。