0

如何从超类构造函数调用子类方法?

示例子类:

<?php
include('../classes/A.php');

class B extends A {
     public function __construct()
    {
        parent::__construct($this->view);
    }
    public function view() {
        //something
    }
}

$b = new B;

?>

示例超类:

<?php
abstract class A
{
    private $callback;

    public function __construct($callback)
    {
        $this->callback = $callback;

        call_user_func($this->callback);
    }   
}
?>

我该怎么做才能让它发挥作用?

4

1 回答 1

1

传递一个包含您的对象实例的数组$this,以及要调用的方法

(参见调用类方法call_user_func手册页的示例 #4 )

class B extends A {
    public function __construct()
    {
        parent::__construct(array($this, 'view'));
    }
    public function view() {
        //something
    }
}
于 2013-03-23T12:04:31.367 回答