Child and parent class property

2019-09-02 03:13发布

I have a class with a name Parent and a class Child that inherits Parent class.Parent class has a property filename with value testfile.In the first step I change the value of this property for example on anothertestvalue in Parent class testFileame method.Then I try to call method log from Child class and this method try to get filename property from Parent class.

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");
}

I expect to get anothertestvalue value but method uses testfile.Can someone explain what happens?

标签: php oop
2条回答
姐就是有狂的资本
2楼-- · 2019-09-02 03:38

I think you misunderstand the notion of CLASS and INSTANCE. You should have an instance of your Child class which calls 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"

Further details here: http://www.php.net/manual/en/language.oop5.php

查看更多
走好不送
3楼-- · 2019-09-02 03:47

Well, you are not setting the value. You just defined a method, that will set the value if called.

So in short, call the method setFilename() and then the value will change.

查看更多
登录 后发表回答