2013-02-10 105 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