[英]Child and parent class property
我有一个名为Parent
的类和一个继承Parent
类的Child
类。 Parent
类有一个属性filename
与值testfile
。在第一步,我改变这个特性,例如价值anothertestvalue
在Parent
类testFileame
method.Then我尝试调用方法log
从Child
类和这个方法试图获取filename
物业Parent
班。
class Parent {
public $filename = 'filename';
public function setFilename() {
$this->filename = 'anotherfilename'
}
public function log($message, $this->filename) {
//here filename from Child class has value 'filename' but I expect 'anotherfilename'
}
}
class Child extends Parent {
$this->log("somemessage");
}
我希望获得另一个anothertestvalue
值,但方法使用testfile
。有人可以解释会发生什么吗?
我认为您误解了CLASS和INSTANCE的概念。 您应该有一个子类的实例,该实例调用setFilename。
class MyParent {
private $filename = 'filename';
public function setFilename($name) {
$this->filename = $name;
}
public function log($message) {
//here filename from Child class has value 'filename' but I expect 'anotherfilename'
print $this->filename;
}
}
class MyChild extends MyParent {
//...
}
$child = new MyChild();
$child->setFilename("anotherfilename");
$child->log("somemessage"); // print "anotherfilename"
此处有更多详细信息: http : //www.php.net/manual/zh/language.oop5.php
好吧,您没有设置该值。 你刚才定义的方法,将设定的值,如果调用。
简而言之,请调用方法setFilename()
,然后该值将更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.