【问题标题】:Inheritance and class scope in PHPInheritance and class scope in PHP
【发布时间】:2022-12-27 19:58:16
【问题描述】:

I'm try learn about inheritance in PHP. A question that I can't get it. I have a block code like following:

class BaseClass {
    private $name = "BaseClass";
    public function getName() {
        echo $this->name;
    }
}

class ChildClass extends BaseClass {
    private $name = "ChildClass";
}

$ob = new ChildClass;
echo $ob->getName(); //result: "BaseClass" . I think its result is "ChildClass".

However, when change visibility of$nametopublicso result is difference.

class BaseClass {
    public $name = "BaseClass";
    public function getName() {
        echo $this->name;
    }
}

class ChildClass extends BaseClass {
    public $name = "ChildClass";
}

$ob = new ChildClass;
echo $ob->getName(); // Result: "ChildClass".

Please help me explain this problem. Thank!

【问题讨论】:

    标签: php oop


    【解决方案1】:

    I think, the reason for this is that private properties are not overwritten. Instead two properties are formed. If you change private to protected, it will work.

    When you call the parent class, your scope will be that of the parent. In your example, private $name exists twice. And because of scope, you'll get the value of the parent property.

    If you do this var_dump($ob), you'll see what I mean:

    object(ChildClass)#1 (2) {
      ["name":"BaseClass":private]=>
      string(9) "BaseClass"
      ["name":"ChildClass":private]=>
      string(10) "ChildClass"
    }
    

    If you overwrite the parent method in the child class, the result will also work, as you change the scope.

    Hope that helps.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多