在子方法中访问父变量
我目前有两个类,一类称为“狗”,一类称为“贵宾犬”。现在我如何使用 Poodle 类中 Dog 中定义的变量。我的代码如下:
class dog {
protected static $name = '';
function __construct($name) {
$this->name = $name
}
}
class Poodle extends dog {
function __construct($name) {
parent::__construct($name)
}
function getName(){
return parent::$name;
}
}
$poodle = new Poodle("Benjy");
print $poodle->getName();
我收到此错误
注意:未定义的变量:名称
I currently have two classes, one called Dog, one called Poodle. Now how can I use a variable defined in Dog from the Poodle class. My code is as follows:
class dog {
protected static $name = '';
function __construct($name) {
$this->name = $name
}
}
class Poodle extends dog {
function __construct($name) {
parent::__construct($name)
}
function getName(){
return parent::$name;
}
}
$poodle = new Poodle("Benjy");
print $poodle->getName();
I get this error
Notice: Undefined variable: name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜“名字”是具体狗的一个属性,所以它首先不应该是静态的。要从继承类中访问非静态父类属性,只需使用“$this”。
i guess 'name' is an attribute of the concrete Dog, so it shouldn't be static in the first place. To access non-static parent class attributes from within an inherited class, just use "$this".
问题出在您的
Dog
构造函数中。您写道:但是使用
$this
意味着name
是一个实例变量,而实际上它是一个静态变量。将其更改为:应该可以正常工作。
The problem is in your
Dog
constructor. You wrote:But using
$this
implies thatname
is an instance variable, when in fact it's a static variable. Change it to this:That should work fine.
在您的狗类中,您已将变量 $name 声明为 static,您必须在声明变量时不使用 static 一词
In your dog class you have declared the variable $name as static, you have to declare the variable without the static word