【发布时间】:2011-07-17 00:58:04
【问题描述】:
您好,我正在尝试使用面向对象编程来了解 inherteince 在 PHP 中的工作原理。主类是Computer,继承类是Mouse。我正在用鼠标类扩展计算机类。我在每个类中都使用 __construct,当我启动类时,我首先使用 pc 类型,如果它之后有鼠标。出于某种原因,计算机返回 null?这是为什么?
class Computer {
protected $type = 'null';
public function __construct($type) {
$this->type = $type;
}
public function computertype() {
$this->type = strtoupper($this->type);
return $this->type;
}
}
class Mouse extends Computer {
protected $hasmouse = 'null';
public function __construct($hasmouse){
$this->hasmouse = $hasmouse;
}
public function computermouse() {
if($this->hasmouse == 'Y') {
return 'This Computer has a mouse';
}
}
}
$pc = new Computer('PC', 'Y');
echo $pc->computertype;
echo $pc->computermouse;
【问题讨论】:
-
不是直接相关的答案,但如果您的计算机对象具有鼠标属性(鼠标类型的对象)会更有意义
-
@Erik I 这个评论对我帮助最大,让我重新思考父类的构建。
标签: php oop inheritance extend