Child and parent class property

2019-09-02 03:00发布

问题:

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?

回答1:

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



回答2:

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.



标签: php oop