gpt4 book ai didi

PHP 类扩展不起作用,为什么这是正确扩展类的方法?

转载 作者:行者123 更新时间:2023-12-02 06:23:24 25 4
gpt4 key购买 nike

您好,我想了解 inherteince 如何使用面向对象编程在 PHP 中工作。主类是Computer,继承类是Mouse。我正在用鼠标类扩展计算机类。我在每个类中都使用 __construct,当我启动类时,我首先使用 pc 类型,如果它之后有鼠标。由于某种原因,计算机返回空值?这是为什么?

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;

最佳答案

这不是继承的工作方式。

继承(又名 extend)允许您根据父类的属性和方法扩展子类。

考虑以下示例:

class Peripheral {
private $connectionType;
private $isConnected = false;

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

function getConnectionType() {
return $this->connectionType;
}

function connect() {
$this->isConnected = true;
}

function disconnect() {
$this->isConnected = false;
}

function isConnected() {
return $this->isConnected;
}
}

您现在可以扩展 Peripheral 类,因为 Mouse 是一个 Peripheral。

class Mouse extends Peripheral {
private $numOfButtons;

function __construct($connectionType, $numberOfButtons) {
parent::__construct($connectionType);
$this->numOfButtons = $numOfButtons;
}

function getNumOfButtons() {
return $this->numOfButtons;
}

function leftClick() {
if($this->isConnected())
echo "Click!";
}

function rightClick() {
if($this->isConnected())
echo "RightClick!";
}
}

现在,因为 MousePeripheral 的子类,所以 Peripheral 中定义的所有方法都可以在 Mouse 中访问>,但反之则不然……

所以虽然我可以这样做:

$mouse = new Mouse('USB', 2);
echo $mouse->getConnectionType(); // USB
$mouse->connect();
$mouse->leftClick();

我不能做以下事情:

$perip = new Peripheral('USB');
echo $perip->getConnectionType(); // USB
$perip->connect();
$perip->leftClick(); // ERROR: leftClick not defined.

关于PHP 类扩展不起作用,为什么这是正确扩展类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5333309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com