为什么 Class 扩展没有得到私有变量

Why is the Class extend not getting private variable

以下代码不会生成名称为 Jock 的输出。我怀疑是因为在 class Animal$nameprivate,但是构造是 public 所以子类应该不能得到 $name 从构造。我不想制作 $name public.

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();

你是对的:删除 private 变量或在 class 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 不会是 public 因为它是 public 构造函数中使用的参数,因此仅限于该函数的范围。狗上的 属性 name 将是 public 但是除非你使用 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";
 }

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

如果您使用的是 Eclipse: 右键单击 class > Source > Generate Getters & Setters

这将为您的所有变量创建函数,如下所示:

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


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

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

私有变量只能在同一个class内部访问,需要对classAnimal.

中的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();