简体   繁体   English

在子方法中访问父变量

[英]Accessing parent variables in child method

I currently have two classes, one called Dog, one called Poodle. 我目前有两堂课,一堂叫狗,一堂叫贵宾犬。 Now how can I use a variable defined in Dog from the Poodle class. 现在如何使用Poodle类中Dog中定义的变量。 My code is as follows: 我的代码如下:

  class dog {
       protected static $name = '';

       function __construct($name) {
            $this->name = $name
       }
  }

  class Poodle extends dog {
       function __construct($name) {
           parent::__construct($name)
       } 

       function getName(){
           return parent::$name;
       }
  }

$poodle = new Poodle("Benjy");
print $poodle->getName();

I get this error 我得到这个错误

Notice: Undefined variable: name 注意:未定义的变量:名称

i guess 'name' is an attribute of the concrete Dog, so it shouldn't be static in the first place. 我想'name'是具体Dog的属性,因此它首先不应该是静态的。 To access non-static parent class attributes from within an inherited class, just use "$this". 要从继承的类中访问非静态父类属性,只需使用“ $ this”。

    class dog {
       protected $name = '';

       function __construct($name) {
            $this->name = $name;
       }
    }

    class Poodle extends dog {
       function getName(){
           return $this->name;
       }
    }

The problem is in your Dog constructor. 问题出在您的Dog构造函数中。 You wrote: 你写了:

$this->name = $name;

But using $this implies that name is an instance variable, when in fact it's a static variable. 但是使用$this表示name是一个实例变量,而实际上它是一个静态变量。 Change it to this: 更改为此:

self::$name = $name;

That should work fine. 那应该工作正常。

In your dog class you have declared the variable $name as static , you have to declare the variable without the static word 在您的dog类中,您已将变量$ name声明为static ,您必须声明不带静态词的变量

class dog {
   protected $name = '';

   function __construct($name) {
        $this->name = $name
   }
}



class Poodle extends dog {
   function __construct($name) {
       parent::__construct($name)
   } 

   function getName(){
       return $this->name;
   }
}

$poodle = new Poodle("Benjy");
print $poodle->getName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM