本节内容:
PHP构造函数
自php5始,可以在类中声明__construct构造方法,当对象被实例化时,该方法被调用。
注意: 
1,如果在继承的子类中没有构造方法而父类中有构造方法,那么当实例化子类时,父类的构造方法会被隐式调用。
2,如果子类有构造方法,父类中也有构造方法,那么子类要显示调用parent::__construct()才能父类的构造方法。
为了向后兼容,如果在php5类中没有找到__construct()方法,它会去找与类名相同的方法名的构造器。
但是,如果同时使用两个构造器,有可能会发生 E_STRICT 级别的错误信息: 
(环境:win32+php5.3.8+apache2.2)
例子:
 
复制代码 代码示例:
<?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:xampphtdocstest3Class.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();  
?>