__construct
__construct是PHP的构造函数,在对象创建时首先被调用,如果子类没有定义构造函数则会从父类继承其构造函数(非私有时),如果子类已经定义了构造函数则不会隐式调用父类的构造函数,子类可以通过parent::__construct(..)的方式调用父类构造函数.构造函数主要在对象创建时进行必要的初始化工作.
特别地,子类的构造函数的参数不需要与父类的构造函数一致,即覆盖时不会报E_STRICT错误
如果子类没有定义__construct(),也没有从父类继承,那么会尝试寻找旧式构造函数(与类同名的函数)(注意:从PHP5.3.3起,在命名空间中,与类同名的方法不再作为构造函数)
__destruct
__destruct是PHP的析构函数,在对象被删除或隐式销毁时被调用. (since PHP5)
例子
<?php
class obj{
public $name = '';
function __construct($name){
echo 'obj_construct call' . PHP_EOL;
$this->name = $name;
}
function __toString(){
return $this->name . PHP_EOL;
}
function __destruct(){
echo 'obj_destruct call' . PHP_EOL;
}
}
class animal extends obj{
public $name = '';
public $height = '';
function __construct($name, $height){
parent::__construct($name);
echo 'animal_construct call' . PHP_EOL;
$this->name = $name;
$this->height = $height;
}
function __toString(){
return $this->name . ': ' . $this->height . PHP_EOL;
}
}
class dog extends animal{
function __destruct(){
echo 'dog_destruct call'.PHP_EOL;
}
}
$d = new dog('dog','90cm');
echo $d;
unset($d);
echo '--------分割线-----' . PHP_EOL;
$a = new animal('animal', '100cm');
echo $a;
unset($a);
/********输出********
obj_construct call
animal_construct call
dog: 90cm
dog_destruct call
--------分割线-----
obj_construct call
animal_construct call
animal: 100cm
obj_destruct call
*********************/