【问题标题】:Why is the Class extend not getting private variable为什么类扩展没有得到私有变量
【发布时间】:2019-02-24 10:08:01
【问题描述】:

以下代码不会生成名称为 Jock 的输出。我怀疑是因为在classAnimal$nameprivate,但构造是public,所以子类应该不能从构造中获取$name。我不想让$namepublic

class Animal{
    private $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function Greet(){
        echo "Hello, I'm some sort of animal and my name is ", $this->name ;
    }
}

 class Dog extends Animal{
     private $type;

     public function __construct($name,$type) {
         $this->type = $type;
           parent::__construct($name);

     }
     public function Greet(){
         echo "Hello, I'm a ", $this->type, " and my name is ", $this->name;
     }
 }
   $dog2 = new Dog('Jock','dog');
   $dog2->Greet();

【问题讨论】:

  • PHP/ 或许将其标记为 PHP

标签: php class private


【解决方案1】:

你是对的:删除 private 变量或在 animal 类的第一行中使用 protected 就可以了。

class Animal{
    protected $name; //see here!
    public function __construct($name) {
        $this->name = $name;
    }
    public function Greet(){
        echo "Hello, I'm some sort of animal and my name is ".$this->name ;
    }
}

$animal = new Animal("Gizmo");
$animal->greet(); //produces the desired result.
echo $animal->name; //this will throw an error - unable to access protected variable $name

$name 不会是公共的,因为它是公共构造函数中使用的参数,因此仅限于该函数的范围。狗身上的属性name 将是公开的,但除非您使用protected

点用于连接字符串。但是echo 允许逗号输出多个表达式。

 public function Greet(){
     echo "Hello, I'm a ".$this->type." and my name is ".$this->name;
 }

在使用双引号时也是如此;您可以将变量放在字符串中:

 public function Greet(){
     echo "Hello, I'm a $this->type and my name is $this->name";
 }

【讨论】:

    【解决方案2】:

    私有变量只能在同一个类内部访问,类Animal中的name变量需要使用protected。

    class Animal{
        protected  $name;
        public function __construct($name) {
            $this->name = $name;
        }
        public function Greet(){
         echo "Hello, I'm some sort of animal and my name is ", $this->name;
      }
    }
    class Dog extends Animal{
     private $type;
    
     public function __construct($name,$type) {
         $this->type = $type;
           parent::__construct($name);
    
     }
     public function Greet(){
         echo "Hello, I'm a ", $this->type, " and my name is ", $this->name;
      }
     }
    $dog2 = new Dog('Jock','dog');
    $dog2->Greet();
    

    【讨论】:

      【解决方案3】:

      您可以使用 setter 和 getter 方法来帮助您修改和检索实例变量,而无需将它们声明为 public。

      如果您使用的是 Eclipse: 右键单击类 > 源 > 生成 Getter & Setter

      这将为您的所有变量创建函数:

      public String getName(){return this.name;}
      
      
      public String setName(String name){this. name = name;  }
      

      然后您可以使用这些方法来访问和编辑您的类变量

      【讨论】:

      • OP使用PHP,这个答案没有提到。
      猜你喜欢
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多