Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

PHP 类属性动态声明时初始化和不初始化的区别是什么?

第一种写法

class test{
    public $a;
    protected $b;
    private $c;
    
    public function __construct($a, $b,$c)
    {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    }
}

第二种写法

class test{
    public function __construct($a, $b,$c)
    {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    }
}

请问这两种写法有什么区别吗还是没有区别,能想到的就是第二种a,b,c三个属性都是为public


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

有区别的
1.执行顺序不一样,类属性初始化调用优先级高于构造函数
2.初始化可以自定义修饰符


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...