【发布时间】:2014-06-28 02:44:34
【问题描述】:
我刚从书中读到:
“在 PHP 5 中,除了构造函数,任何派生类在覆盖方法时都必须使用相同的签名”
来自 cmets 中的 PHP 手册:
"在覆盖中,方法名称和参数(arg's)必须相同。
示例:
类 P { 公共函数 getName(){} }
C 类扩展 P{ public function getName(){} }
"
那么为什么我可以用其他参数和它们的数量来替换方法呢?这是合法的还是将来会触发错误,或者我只是错过了一些东西?
PHP 版本 5.5.11
class Pet {
protected $_name;
protected $_status = 'None';
protected $_petLocation = 'who knows';
// Want to replace this function
protected function playing($game = 'ball') {
$this->_status = $this->_type . ' is playing ' . $game;
return '<br>' . $this->_name . ' started to play a ' . $game;
}
public function getPetStatus() {
return '<br>Status: ' . $this->_status;
}
}
class Cat extends Pet {
function __construct() {
$this->_type = 'Cat';
echo 'Test: The ' . $this->_type . ' was born ';
}
// Replacing with this one
public function playing($gameType = 'chess', $location = 'backyard') {
$this->_status = 'playing ' . $gameType . ' in the ' . $location;
return '<br>' . $this->_type . ' started to play a ' . $gameType . ' in the ' . $location;
}
}
$cat = new Cat('Billy');
echo $cat->getPetStatus();
echo $cat->playing();
echo $cat->getPetStatus();
这将输出:
测试:猫出生了
状态:无
猫开始在后院下棋
现状:在后院下棋
【问题讨论】:
-
开启错误显示并将错误级别设置为E_ALL
-
什么都没发生,它没有显示任何错误。
标签: php