are not called implicitly
php.net
1 <?php 2 class BaseClass{ 3 function __construct() 4 { 5 print "In BaseClass constructor<br>"; 6 } 7 } 8 9 class SubClass extends BaseClass{ 10 function __construct() 11 { 12 // parent::__construct(); 13 print "In SubClass constructor<br>"; 14 } 15 } 16 17 class OtherSUbClass extends BaseClass{ 18 19 } 20 $obj = new BaseClass(); 21 $obj = new SubClass(); 22 $obj = new OtherSubClass();
In BaseClass constructor
In SubClass constructor
In BaseClass constructor
1 <?php 2 class BaseClass{ 3 function __construct() 4 { 5 print "In BaseClass constructor<br>"; 6 } 7 } 8 9 class SubClass extends BaseClass{ 10 function __construct() 11 { 12 parent::__construct(); 13 print "In SubClass constructor<br>"; 14 } 15 } 16 17 class OtherSUbClass extends BaseClass{ 18 19 } 20 $obj = new BaseClass(); 21 $obj = new SubClass(); 22 $obj = new OtherSubClass();
In BaseClass constructor
In BaseClass constructor
In SubClass constructor
In BaseClass constructor
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
<?php class MyDestructableClass{ function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; } function __destruct() { // TODO: Implement __destruct() method. print "Destroying ".$this->name."\n"; } } $obj = new MyDestructableClass();
In constructor Destroying MyDestructableClass
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
PHP 5 引入了析构函数的概念,这类似于其它面向对象的语言,如 C++。析构函数会在到某个对象的所有引用都被删除或者当对象被显式销毁时执行。
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body. Also like constructors, a child class may inherit the parent's destructor if it does not implement one itself.
The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing. 和构造函数一样,父类的析构函数不会被引擎暗中调用。要执行父类的析构函数,必须在子类的析构函数体中显式调用 parent::__destruct()。此外也和构造函数一样,子类如果自己没有定义析构函数则会继承父类的。
析构函数即使在使用 exit() 终止脚本运行时也会被调用。在析构函数中调用 exit() 将会中止其余关闭操作的运行。