简体   繁体   中英

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. Is it possible?

Sounds to me like you're merely asking for how to pass a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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