简体   繁体   English

在PHP中传递对函数的引用

[英]Passing a reference to a function in PHP

I saw some similar questions but none were exactly what I need. 我看到了一些类似的问题,但我所需要的都不是。
I have the following classes: 我有以下课程:

abstract class A
{
    abstract function foo(); 

    public function callingD()
    {
         D::doSomething($this->foo());  //something like that
    }
}

class B extends A
{
    function foo()
    {
       //some code
    }
}

class C extends A
{
    function foo()
    {
       //some code
    }
}

class D
{
    public static function doSomething($fooImp)
    {
       //some code
    }
}

Now, what I want is to call D::doSomething from a function in class A and that one of the parameters for doSomething will be the implementation of foo in A 's current instance. 现在,我要从类A的函数调用D::doSomething ,而doSomething的参数之一将是A的当前实例中foo的实现。 Is it possible? 可能吗?

Sounds to me like you're merely asking for how to pass a callable ; 在我看来,您只是在询问如何传递callable the dance and song about abstract classes is pretty irrelevant: 关于抽象类的舞蹈和歌曲是完全不相关的:

abstract class A {
    abstract function foo(); 

    public function callingD() {
         D::doSomething([$this, 'foo']);
    }
}

class D {
    public static function doSomething(callable $fun) {
       $fun();
    }
}

That's all there is to it. 这里的所有都是它的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM