Heim  >  Artikel  >  Backend-Entwicklung  >  对PHP构造函数的理解

对PHP构造函数的理解

巴扎黑
巴扎黑Original
2016-11-23 11:35:471066Durchsuche

做项目的时候遇到了一些错误,最终分析,是php的构造方法在作怪,这里重新整理了一下: 
php5开始可以在类中声明__construct构造方法,当对象被实例化的时候,该方法被调用。 
注意: 
1.如果在继承的子类中没有构造方法而父类中有构造方法,那么当实例化子类时,父类的构造方法会被隐式调用。
2.如果子类有构造方法,父类中也有构造方法,那么子类要显示调用parent::__construct()才能父类的构造方法。 

为了向后兼容,如果在php5类中没有找到__construct()方法,它会去找与类名相同的方法名的构造器,但是如果同时使用两个构造器,有可能会发生 E_STRICT 级别的错误信息: 
(以下代码是本人web环境:win32+php5.3.8+apache2.2测试) 

<?php
class B{
//构造器
public function B(){
echo &#39;this is B()&#39;;
}
public function __construct(){
echo &#39;this is __construct()&#39;;
}
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 &#39;this is __construct()&#39;;
}
public function X(){
echo &#39;this is X()&#39;;
}
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 &#39;this is __construct() called Y()&#39;;
// do init
}
public function other(){
//do something
}
}
$y = new Y();
?>


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:smarty二维数组读取Nächster Artikel:php邮件发送