PHP构造函数的执行顺序

测试代码如下:
<?php
class grandfather {
    public function __construct(){
        echo 'grandfather';
    }
}
class father extends grandfather {
    public function __construct(){
        echo 'father';
    }
}
class son extends father {
    public function __construct(){
        echo 'son';
    }
}
$test = new son();
结果是 :   son
<?php
class grandfather {
    public function __construct(){
        echo 'grandfather';
    }
}
class father extends grandfather {
    public function __construct(){
        echo 'father';
    }
}
class son extends father {
    
}
$test = new son();
结果: father
<?php
class grandfather {
    public function __construct(){
        echo 'grandfather';
    }
}
class father extends grandfather {

}
class son extends father {
    
}
$test = new son();
结果:grandfather

由此可见php类的构造函数调用是 从自身向上查找,执行最近的一个,然后stop

相关文章:

  • 2022-03-06
  • 2021-09-20
  • 2022-12-23
  • 2022-01-13
  • 2022-01-14
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
相关资源
相似解决方案