我如何共享父类的逻辑和功能?

时间:2012-01-07 12:52:32

标签: php class

我想在父类中添加其他内容。 我无法修改父类,因为升级软件时将删除所有修改。所以我想扩展课程。我可以在子类中添加它而不重复父函数吗?

class parent
{
    public function __construct()
    {
        // lots of logic to hook up following functions with main software
    }

      // lots of parent functions
}

class child extends parent
{
     function __construct()
    {
        // Is this going to share parent's logic and hook up with those actions?
        // Or, should I repeat those logics?
        parent::__construct();

        // add child addicional logic
    }
     // child functions
    // should I repeat parent's functions? I need the parent take child along all the jobs.

}

2 个答案:

答案 0 :(得分:2)

是的,这是正确的方法。

class parent
{
    public function __construct()
    {
        // lots of logic to hook up following functions with main software
    }
    // lots of parent functions

    protected function exampleParentFunction()
    {
        //do lots of cool stuff
    }
}

class child extends parent
{
     function __construct()
    {
        // This will run the parent's constructor
        parent::__construct();
        // add child additional logic
    }
    // child functions
    public function exampleChildFunction();
    {
        $result = $this->exampleParentFunction();
        //Make result even cooler :)
    }
    //or you can override the parent methods by declaring a method with the same name
    protected function exampleParentFunction()
    {
        //use the parent function
        $result = parent::exampleParentFunction();
        //Make result even cooler :)
    }
}

根据您最近的问题,您真的需要阅读一本关于PHP OOP的书。从手册http://www.php.net/oop

开始

答案 1 :(得分:0)

是的,正如vascowhite所说,这是正确的做法。
至于重复的父函数,您不必这样做,除非您想要为这些函数添加额外的逻辑。 e.g。

class foo {
    protected $j;
    public function __construct() {
        $this->j = 0;
    }
    public function add($x) {
        $this->j += $x;
    }
    public function getJ() {
        return $this->j;
    }
}

class bar extends foo {
    protected $i;
    public function __construct() {
        $this->i = 0;
        parent::__construct();
    }
    public function add($x) {
        $this->i += $x;
        parent::add($x);
    }
    public function getI() {
        return $this->i;
    }
    // no need to redo the getJ(), as that is already defined.

}