以下代码不会生成名为 Jock
的输出。我怀疑是因为在 class
Animal
中 $name
是 private
,但构造是 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
变量或在 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)构造函数中使用的参数,因此仅限于该函数的范围。但是,除非您使用protected
,否则狗的属性name
将是公开的。
点用于连接字符串。但是 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";
}
关于php - 为什么类扩展没有获得私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850799/