我正在研究與此問題略有相似的其他問題。我試圖做的是創建一個具有私有屬性的類(或者一些不知道它到底叫什么的東西)并私下存盤在一個類中,然后像這樣進行繼承:
(我想進一步澄清我的解釋,但我的編程詞匯非常有限)
<?php
class Fruit {
private $name;
private $color;
public function patients($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo $this->intro();
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
?>
uj5u.com熱心網友回復:
是的你可以。new Strawberry("Strawberry", "red");如果您還沒有設定并且不想使用它,則應該使用您宣告的方法,而不是使用建構式 ( ):
<?php
class Fruit {
private $name;
private $color;
public function describe($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo $this->intro();
}
}
重新命名方法patients(),以describe()更恰當。洗掉了你的方法,assignPatient()因為你沒有使用它,它基本上做了同樣的事情describe()。您現在可以使用
$strawberry = new Strawberry();
$strawberry->describe("Strawberry", "red");
$strawberry->message();
輸出“水果是草莓,顏色是紅色。 ”。
事實上,您也可以洗掉您的message()方法并呼叫intro():
$strawberry = new Strawberry();
$strawberry->describe("Strawberry", "red");
$strawberry->intro();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356492.html
