2010-04-02 73 views
3

我有一個類:php擴展,但有一個新的構造函數...可能嗎?

class test { 
    function __construct() { 
     print 'hello'; 
    } 
    function func_one() { 
     print 'world'; 
    } 
} 

什麼,我想這樣做是有那種擴展測試類的類。我說'排序',因爲類需要能夠運行測試類能夠運行的任何函數,但是除非我問它,否則不要運行構造。我不想重寫構造。任何人有任何想法如何實現這一目標?

+0

不使用構造函數即可。沒有什麼「擴展」。 – DarthVader 2010-04-02 03:53:29

+0

@ user177883是的。 – 2010-04-02 04:59:47

+0

@帕特里克:目前尚不清楚你想要什麼樣的行爲。也許如果你說明了你的總體目標,這將更容易理解。我們也可能會想到一個更好的方法。 – outis 2010-04-02 18:12:46

回答

5
class test { 
    function __construct() { 
     print 'hello'; 
    } 
    function func_one() { 
     print 'world'; 
    } 
} 


class test_2 extends test { 
    function __construct() { 
     if (i want to) { 
      parent::__construct(); 
     } 
    } 
} 
+0

在任何情況下,一旦你實例化一個新的測試對象,構造函數將被執行。對不起,但這可能是誤導。 – DarthVader 2010-04-02 03:55:05

+2

@ user177883:在php中,您可以省略父類的構造函數(僅僅通過在派生類的構造函數中不顯式調用它)。我不喜歡它,但是就是這樣。 – VolkerK 2010-04-02 04:12:05

1

重寫構造有什麼問題?

class foo extends test { 
    function __construct() { } 
} 

$bar = new foo(); // Nothing 
$bar->func_one(); // prints 'world' 
0

你可以定義你的子類是「preConstructor」的方法,你的根類的構造函數將執行,並使用一個布爾標誌,以確定構造函數代碼是否應該執行。

像這樣:

 
class test 
{ 
    protected $executeConstructor; 

    public function __construct() 
    { 
     $this->executeConstructor = true; 
     if (method_exists($this, "preConstruct")) 
     { 
      $this->preConstruct(); 
     } 

     if ($this->executeConstructor == true) 
     { 
      // regular constructor code 
     } 
    } 
} 

public function subTest extends test 
{ 
    public function preConstruct() 
    { 
     $this->executeConstructor = false; 
    } 
} 
+0

Coronatus的代碼在功能上是等同的,錯誤的可能性較小。但是,這將默認執行父構造函數,而他不會。帕特里克最好選擇哪一個。 – outis 2010-04-02 18:22:54

+0

@outis:OP的要求之一是「我不想重寫構造。」在這方面,Coronatus的代碼在功能上並不相同。 – Adrian 2010-04-02 22:58:25

+0

,它更像帕特里克對「延伸的種類」一詞的解釋的一部分,以及他關於它如何工作的想法。首先,注意措辭「不想」而不是「不能」。即使情況並非如此,這是一個設計約束,而不是一個功能約束。問題中的含糊不清使得很難知道哪個答案更合適。 – outis 2010-04-03 00:15:55

相關問題