【问题标题】:PHP override function of a single instancePHP单实例覆盖函数
【发布时间】:2016-05-03 08:06:29
【问题描述】:

在 javascript 中,我知道可以简单地覆盖单个实例的类方法,但我不太确定这在 PHP 中是如何管理的。 这是我的第一个想法:

class Test {
    public $var = "placeholder";
    public function testFunc() {
        echo "test";
    }
}

$a = new Test();

$a->testFunc = function() {
    $this->var = "overridden";
};

我的第二次尝试是匿名函数调用,不幸的是杀死了 object 范围...

class Test {
    public $var = "placeholder";
    public $testFunc = null;
    public function callAnonymTestFunc() {
        $this->testFunc();
    }
}

$a = new Test();

$a->testFunc = function() {
    //here the object scope is gone... $this->var is not recognized anymore
    $this->var = "overridden";
};

$a->callAnonymTestFunc();

【问题讨论】:

  • 我不确定您为什么要这样做。仅仅是设置属性吗?还是有其他功能?
  • 您要覆盖类还是对象级别?如果在类级别,您可以简单地扩展您的类并以这种方式覆盖函数。如果在对象级别,您可以将回调传递给构造函数。
  • 它将在对象级别,您能否进一步解释“您可以将回调传递给构造函数”的意思?提前致谢!
  • 我发现了一个类似的线程。 Custom anonymous function
  • 我们在这里讨论的是哪个 PHP 版本?

标签: php oop overriding


【解决方案1】:

为了完全理解您在此处尝试实现的目标,首先应该知道您想要的 PHP 版本,PHP 7 比任何以前的版本都更适合 OOP 方法。

如果您的匿名函数的绑定是问题,您可以 bind the scope of a function 从 PHP >= 5.4 到一个实例,例如

$a->testFunc = Closure::bind(function() {
    // here the object scope was gone...
    $this->var = "overridden";
}, $a);

从 PHP >= 7 开始,您可以在创建的闭包上立即调用 bindTo

$a->testFunc = (function() {
    // here the object scope was gone...
    $this->var = "overridden";
})->bindTo($a);

尽管您尝试实现的目标的方法超出了我的想象。也许你应该尝试明确你的目标,我会尝试所有可能的解决方案。

【讨论】:

  • 不幸的是,如果 class 有魔法方法(如 Laravel User 模型,上面只设置 db-column)怎么办?
【解决方案2】:

我会使用适用于大多数高级语言的 OOP 继承原则:

Class TestOverride extends Test {
public function callAnonymTestFunc() {
//overriden stuff
}
}

$testOverriden = new TestOverriden();
$testOverriden->callAnonymTestFunc();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 2014-09-19
    相关资源
    最近更新 更多