欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于php继承的问题

程序员文章站 2022-04-21 11:52:28
...
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 )

想要$one对象改变了dog属性之后,$two对象的dog属性也跟着改变,就要引用的那样,不知道要怎样实现?

回复内容:

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 )

想要$one对象改变了dog属性之后,$two对象的dog属性也跟着改变,就要引用的那样,不知道要怎样实现?

static 静态关键字

    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 )

单例 静态属性

补充@ 徐先生的背影

LZ应该注意代码中的parent,parent指向父类
如果换成self那么就是指向当前类

@徐先生的背影 的回答解决了你的问题,但是我觉得你可能对类和对象的理解有问题。 @pang20c 的答案就是我指的。
你把你那句 $two=new two() 改为 $two=new one() 结果还是一样的。

    print_r($one->dog);//Array ( [color] => yellow [age] => 3 )
    print_r($two->dog);//Array ( [color] => red [age] => 3 )

也可能是我想多了。。。。不过问题基本解决了

class two extends one{
}
相关标签: php