我可以在不使用 __constructor 的情况下完成这项工作吗
can i make this work without using __constructor
我正在研究与此问题略有相似的其他问题。我想做的是制作一个 class 具有私有属性(或者不知道到底叫什么的东西)并私下存储在 class 中,然后像这样进行继承:
(我想进一步澄清我的解释,但我的编程词汇量非常有限)
<?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();
?>
是的,你可以。你应该使用你声明的方法而不是使用构造函数(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();
我正在研究与此问题略有相似的其他问题。我想做的是制作一个 class 具有私有属性(或者不知道到底叫什么的东西)并私下存储在 class 中,然后像这样进行继承:
(我想进一步澄清我的解释,但我的编程词汇量非常有限)
<?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();
?>
是的,你可以。你应该使用你声明的方法而不是使用构造函数(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();