Php 为什么类extend没有获取私有变量
以下代码不会生成名为Php 为什么类extend没有获取私有变量,php,class,private,Php,Class,Private,以下代码不会生成名为Jock的输出。我怀疑是因为在类中动物的$name是私有的,但是构造是公共的,所以子类应该不能从构造中获取$name。我不想将$name公开 class Animal{ private $name; public function __construct($name) { $this->name = $name; } public function Greet(){ echo "Hello, I'm som
Jock
的输出。我怀疑是因为在类中动物的$name
是私有的
,但是构造是公共的
,所以子类应该不能从构造中获取$name
。我不想将$name
公开
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
不会是公共的,因为它是公共构造函数中使用的参数,因此仅限于该函数的范围。狗的属性名称
将是公共的,除非您使用保护
圆点用于连接字符串。但是,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方法来帮助您修改和检索实例变量,而无需将它们声明为公共变量
如果您使用的是eclipse:
右键单击类>源>生成getter和setter
这将为所有变量创建函数,如下所示:
public String getName(){return this.name;}
public String setName(String name){this. name = 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();
PHP/也许将其标记为PHP OP使用PHP,这个答案并不是指这个。