2013-02-10 108 views
0

可能是個愚蠢的問題..但是如何正確使用類Tests中的類Test的方法而不重寫它們呢?擴展時使用父類的方法

<?php 
class Test { 

    private $name; 

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

    public function getName() { 
     return $this->name; 
    } 

} 

<?php 

class Testb extends Test { 

    public function __construct() { 
     parent::__construct($name); 
    } 

} 

<?php 

include('test.php'); 
include('testb.php'); 

$a = new Test('John'); 
$b = new Testb('Batman'); 

echo $b->getName(); 
+1

您獲得的當前輸出是多少? – Achrome 2013-02-10 22:07:24

+0

我什麼都沒有得到.. – Reshad 2013-02-10 22:08:33

回答

1

你需要給Testb構造一個$name參數太多,如果你希望能夠用這樣的說法來初始化它。我修改了你的Testb類,以便它的構造函數實際上有一個參數。你目前擁有它的方式,你不應該能夠初始化你的課程Testb。我使用的代碼如下:

<?php 
class Test { 

    private $name; 

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

    public function getName() { 
     return $this->name; 
    } 

} 

class Testb extends Test { 

    // I added the $name parameter to this constructor as well 
    // before it was blank. 
    public function __construct($name) { 
     parent::__construct($name); 
    } 

} 

$a = new Test('John'); 
$b = new Testb('Batman'); 

echo $a->getName(); 
echo $b->getName(); 
?> 

也許你沒有啓用錯誤報告?無論如何,您都可以在此驗證我的結果:http://ideone.com/MHP2oX

+0

啊哈這是我錯過的部分我沒有在調用父構造函數時在我的子類中添加參數:)謝謝! – Reshad 2013-02-10 22:12:57