2012-01-07 5 views
0

親クラスに追加のものを追加したいと思います。 ソフトウェアのアップグレード時にすべての変更が消去されるため、親クラスは変更できません。だからクラスを拡張したい。親関数を繰り返さずに子クラスに追加することはできますか?親クラスのロジックと関数をどのように共有できますか?

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

変更する部品をオーバーライドするだけで済みます。追加のコードに加えて親コードを実行する必要がある場合は、 'parent :: *'を呼び出す必要があります。親クラスのロジックを実行したい場合は、あなたのctorの場合は 'parent :: __ construct()'を呼び出す必要があります。あなたが過負荷にならない場合は、親からのメソッドを追加する必要はありません。 – Gordon

答えて

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

+0

素晴らしい!それはまさに私がやりたいことです。 – Jenny

+0

あなたのアドバイスをありがとう。私は問題が発生したときにphpマニュアルで関数を探していましたが、慎重に研究する時間を割いていませんでした。たぶん、この上手な仕事をする時が来ました。 – Jenny

0

はい、vascowhiteが言ったとおり、それは正しい方法です。
親関数を繰り返す場合、それらの関数にもロジックを追加しない限り、必要はありません。例えば

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. 

} 
関連する問題