2013-07-14 46 views
0

我有这个抽象类抽象类的构造函数中重写混淆

abstract class Guitar { 

     protected $strings; 

     public function __construct($no_of_strings) { 
      $this->strings = $no_of_strings; 
      echo 'Guitar class constructor is called <br/>'; 
     } 

     abstract function play(); 
    } 

而子类,

class Box_Guitar extends Guitar { 

    public function __construct($no_of_strings) { 
     echo 'Box Guitar constructor is called <br/>'; 
     $this->strings = $strings + 100; 
    } 

    public function play() { 
     echo 'strumming ' . $this->strings; 
    } 

} 

然后,我开始与阶级,

$box_guitar = new Box_Guitar(6); 

而且我出来放了

箱吉他构造函数被调用

吉他类构造函数被调用

拨弄106

所以我的问题是,为什么父类的构造被称为?我没有使用Parent :: __ construct()。

回答

1

不是。

当我跑你上面给的代码,我得到这样的输出:

箱吉他构造函数被调用
注意:未定义的变量:字符串/test/test.php第19行

仔细检查你没有运行旧版本的文件或其他东西。你忘了保存还是上传一些更改?


为了记录在案,一旦你弄清楚为什么你得到意外的行为,正确的方式来写Box_Guitar构造可能会是这个样子:

public function __construct($no_of_strings) { 
    echo 'Box Guitar constructor is called <br/>'; 
    parent::__construct($no_of_strings + 100); 
} 
+0

让我检查......... – Namal

+0

+1代码先测试:) – 2013-07-14 08:17:40

+0

我加了一个答案.... – Namal

0

感谢@jcsanyi。有我的错。我有另一个类叫

class Electric_Guitar extends Guitar { 

    public function play() { 
     return 'Plug to current : '. $this->strings; 
    } 
} 

这没有任何构造函数。当我调用对象时,我使用了它们两个。

$box_guitar = new Box_Guitar(6); 
$elec_guitar = new Electric_Guitar(5); 

所以abstrct构造函数被elec_guitar对象调用。