开发者

Executing calling class' method

开发者 https://www.devze.com 2023-02-10 04:23 出处:网络
class Car { $gas= new Gas(); $gas->fill( \'filledHandler\' ); function filledHandler() { echo \'Gas has been filled!\';
class Car
{
    $gas= new Gas();
    $gas->fill( 'filledHandler' );

    function filledHandler()
    {
        echo 'Gas has been filled!';
    }
}

class Gas
{
    function fill( $function )
    {
        // do something here
        $function(); 
    }
}

I need to call $function of开发者_StackOverflow中文版 calling class. Right now, it's looking for a global function


You have to pass the calling instance.

class Car
{
    function fillGas()
    {
        $gas = new Gas();
        $gas->fill($this, 'filledHandler');
    }

    function filledHandler()
    {
        echo 'Gas has been filled!';
    }
}

class Gas
{
    function fill($obj, $function)
    {
        // If you need the class name, use get_class($obj)
        $obj->$function();
    }
}


class Car
{
    function __construct()
    {
      $gas= new Gas();
      $gas->fill($this, 'filledHandler' );
    }

    function filledHandler()
    {
        echo 'Gas has been filled!';
    }
}

class Gas
{
    function fill($object, $function )
    {
        $object->$function();
    }
}

(Ask more question (like what exactly do you want to happen anyway) and get more answer text ^^.)

0

精彩评论

暂无评论...
验证码 换一张
取 消