1、构造方法 __construct()
主要用来在创建对象时初始化对象,向对象成员变量赋予初始值,在创建对象的语句中与 new 运算符一起使用。
2、析构方法 __destruct()
析构函数(destruct) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。
3、PHP 不会在子类的构造方法中自动的调用父类的构造方法。要执行父类的构造方法,需要在子类的构造方法中调用 parent::__construct() 。
列:
class maxbox
{
var $name;
//构造函数
function __construct()
{
$this->name = '红盒子';
}
//析构函数
function __destruct()
{
$this->name = '蓝盒子';
}
}
class box extends maxbox
{
public $width = '100px';
public $height = '200px';
//构造函数
function __construct($w,$h)
{
//调用父类构造/析构方法
parent::__construct();
parent::__destruct();
$this->width = $w;
$this->height = $h;
//输出父类的属性值
echo $this->name;
}
public function setWH($w,$h)
{
$this->width = $w;
$this->height = $h;
}
//析构函数
function __destruct()
{
echo '执行完毕';
echo $this->width = 0;
echo $this->height = 0;
}
}
$box = new box('300px','500px');
echo $box->width;
echo $box->height;
$box->setWH('600px','700px');
echo $box->width;
echo $box->height;