执行调用类的方法

时间:2011-02-10 08:51:23

标签: php oop

class Car
{
    $gas= new Gas();
    $gas->fill( 'filledHandler' );

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

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

我需要调用$ function调用类。现在,它正在寻找全球功能

2 个答案:

答案 0 :(得分:4)

你必须传递调用实例。

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();
    }
}

答案 1 :(得分:0)

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();
    }
}

(提出更多问题(比如你究竟想要发生什么)并获得更多答案文本^^。)