PHP 构造函数和析构函数
phpserver side programmingprogramming更新于 2025/7/18 22:52:17
简介
在面向对象编程术语中,构造函数是在类内部定义的方法,在创建对象时自动调用。构造函数方法的目的是初始化对象。在 PHP 中,一个特殊名称为 __construct 的方法充当构造函数。
语法
__construct ([ mixed $args = "" [, $... ]] ) : void
构造函数示例
此示例显示构造函数在声明对象时自动执行
示例
<?php
class myclass{
function __construct(){
echo "object initialized";
}
}
$obj=new myclass();
?>
输出
这将产生以下结果。−
object initialized
带参数的构造函数
类属性由带参数的构造函数初始化
示例
<?php
class rectangle{
var $height;
var $width;
function __construct($arg1, $arg2){
$this->height=$arg1;
$this->width=$arg2;
}
function show(){
echo "Height=$this->height Width=$this->width";
}
}
$obj=new rectangle(10,20);
$obj->show();
?>
输出
这将产生以下结果。−
Height=10 Width=20
继承中的构造函数
如果父类中定义了构造函数,则可以在子类的构造函数中通过 parent::__construct 调用它。但是,如果子类没有定义构造函数,它将从基类继承相同的构造函数。
示例
<?php
class a{
function __construct(){
echo "this is a constructor of base class
";
}
}
class b extends a{
function __construct(){
parent::__construct();
echo "this a constructor class b
";
}
}
class c extends a {
//
}
$a=new a();
$b=new b();
$c=new c();
?>
输出
这将产生以下结果。−
this is a constructor of base class this is a constructor of base class this a constructor class b this is a constructor of base class
析构函数
析构函数是垃圾收集器发现特定对象不再被引用时自动执行的方法。在 PHP 中,析构函数名为 __destruct。在关闭过程中,对象也会被销毁。析构函数不接受任何参数,也不返回任何数据类型。
示例
<?php
class myclass{
function __construct(){
echo "object is initialized
";
}
function __destruct(){
echo "object is destroyed
";
}
}
$obj=new myclass();
?>
输出
这将显示以下结果
object is initialized object is destroyed

