Maison >développement back-end >tutoriel php >关于php继承的问题
<code>class base{ public $dog = array('color'=>'red','age'=>3); } class one extends base{ public function set($key,$value) { $this->dog[$key] = $value; } } class two extends base{ public function set($key,$value) { $this->dog[$key] = $value; } } $one = new one(); $two = new two(); $one->set('color','yellow'); print_r($one->dog);//Array ( [color] => yellow [age] => 3 ) print_r($two->dog);//Array ( [color] => red [age] => 3 ) </code>
想要$one对象改变了dog属性之后,$two对象的dog属性也跟着改变,就要引用的那样,不知道要怎样实现?
<code>class base{ public $dog = array('color'=>'red','age'=>3); } class one extends base{ public function set($key,$value) { $this->dog[$key] = $value; } } class two extends base{ public function set($key,$value) { $this->dog[$key] = $value; } } $one = new one(); $two = new two(); $one->set('color','yellow'); print_r($one->dog);//Array ( [color] => yellow [age] => 3 ) print_r($two->dog);//Array ( [color] => red [age] => 3 ) </code>
想要$one对象改变了dog属性之后,$two对象的dog属性也跟着改变,就要引用的那样,不知道要怎样实现?
static 静态关键字
<code> class base{ public static $dog = array('color'=>'red','age'=>3); } class one extends base{ public function set($key,$value) { parent::$dog[$key] = $value; } } class two extends base{ public function set($key,$value) { parent::$dog[$key] = $value; } } $one = new one(); $two = new two(); $one->set('color','yellow'); print_r($one::$dog);//Array ( [color] => yellow [age] => 3 ) print_r($two::$dog);//Array ( [color] => red [age] => 3 ) </code>
单例 静态属性
补充@ 徐先生的背影
LZ应该注意代码中的parent,parent指向父类
如果换成self那么就是指向当前类
@徐先生的背影 的回答解决了你的问题,但是我觉得你可能对类和对象的理解有问题。 @pang20c 的答案就是我指的。
你把你那句 $two=new two()
改为 $two=new one()
结果还是一样的。
<code> print_r($one->dog);//Array ( [color] => yellow [age] => 3 ) print_r($two->dog);//Array ( [color] => red [age] => 3 ) </code>
也可能是我想多了。。。。不过问题基本解决了
<code>class two extends one{ } </code>