子类和父类属性 [英] Child and parent class property

查看:68
本文介绍了子类和父类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Parent 的类和一个继承 Parent 类的类 Child.Parent 类有一个属性 filename,值为 testfile.在第一步中,我更改了这个属性的值,例如在 Parentanothertestvalue 上/code> class testFileame 方法.然后我尝试从 Child 类调用方法 log 并且此方法尝试获取 filenameParent 类的 code> 属性.

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

我希望获得 anothertestvalue 值,但方法使用 testfile.有人能解释一下会发生什么吗?

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

推荐答案

我想你误解了 CLASS 和 INSTANCE 的概念.您应该有一个调用 setFilename 的 Child 类的实例.

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"

更多详情请见:http://www.php.net/manual/en/language.oop5.php

这篇关于子类和父类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆