时间:2021-07-01 10:21:17 帮助过:25人阅读
<?php
class B{
//构造器
public function B(){
echo 'this is B()';
}
public function __construct(){
echo 'this is __construct()';
}
public function other(){
//do something
}
}
$b = new B();
?>结果:Strict Standards: Redefining already defined constructor for class B in D:\xampp\htdocs\test3\Class.php on line 8
this is __construct()
但仅调换下方法的位置结果却不一样:
<?php
class X{
//构造器
public function __construct(){
echo 'this is __construct()';
}
public function X(){
echo 'this is X()';
}
public function other(){
//do something
}
}
$x = new X();
?>其实,从php5.3.3开始,与类名相同的方法不再做为类的构造方法,命名空间类也一样,要是使用的是php5.3.3以上的版本,就不能使用与类同名的方法作为构造方法了:
<?php
namespace Foo;
class Bar {
public function Bar() {
// PHP 5.3.0-5.3.2 是构造方法
// PHP 5.3.3 被当做是正常的方法使用
}
}
?>如果非要在php5.3.3以上同时使用两个构造器,那么可以这样:
<?php
class Y{
//构造器
public function __construct(){
self::Y();
}
public function Y(){
echo 'this is __construct() called Y()';
// do init
}
public function other(){
//do something
}
}
$y = new Y();
?>