关于php继承的问题

WBOY
Release: 2016-06-06 20:37:10
Original
891 people have browsed it

<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>
Copy after login
Copy after login

想要$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>
Copy after login
Copy after login

想要$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>
Copy after login

单例 静态属性

补充@ 徐先生的背影

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>
Copy after login

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

<code>class two extends one{
}
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template