I encountered some errors while working on the project. In the final analysis, it was the PHP constructor method that caused the problem. Here is a re-arrangement:
Starting with PHP5, you can declare the __construct constructor method in the class. When the object is instantiated, this method is called.
Note:
1. If there is no constructor method in the inherited subclass but there is a constructor method in the parent class, then when the subclass is instantiated, the constructor method of the parent class will be implicitly called.
2. If the subclass has a constructor and the parent class also has a constructor, then the subclass must explicitly call parent::__construct() to access the parent class's constructor.
For backward compatibility, if the __construct() method is not found in the php5 class, it will look for a constructor with the same method name as the class name, but if two constructors are used at the same time, E_STRICT level may occur Error message:
(The following code is my web environment: win32+php5.3.8+apache2.2 test)
<?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(); ?>
Result: Strict Standards: Redefining already defined constructor for class B in D:xampphtdocstest3Class.php on line 8
this is __construct()
But just changing the position of the method is different and the result is different:
<?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(); ?>
In fact, starting from php5.3.3, the method with the same name as the class is no longer used as the constructor of the class, and the same is true for namespace classes. If you are using php5.3.3 or above, you cannot use the method with the same name as the class as the constructor:
<?php namespace Foo; class Bar { public function Bar() { // PHP 5.3.0-5.3.2 是构造方法 // PHP 5.3.3 被当做是正常的方法使用 } } ?>
If you have to use two constructors at the same time on php5.3.3 or above, then you can do this:
<?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(); ?>