PHP(十一)建構函式

2021-08-31 11:54:20 字數 651 閱讀 6801

1、構造方法 __construct()

主要用來在建立物件時初始化物件,向物件成員變數賦予初始值,在建立物件的語句中與 new 運算子一起使用。

2、析構方法 __destruct()

析構函式(destruct) 與建構函式相反,當物件結束其生命週期時(例如物件所在的函式已呼叫完畢),系統自動執行析構函式。

3、php 不會在子類的構造方法中自動的呼叫父類的構造方法。要執行父類的構造方法,需要在子類的構造方法中呼叫 parent::__construct() 。

列:

class maxbox

//析構函式

function __destruct()

}class box extends maxbox

public function setwh($w,$h)

//析構函式

function __destruct()

}$box = new box('300px','500px');

echo $box->width;

echo $box->height;

$box->setwh('600px','700px');

echo $box->width;

echo $box->height;

php 建構函式

php 5 允行開發者在乙個類中定義乙個方法作為建構函式。具有建構函式的類會在每次建立新物件時先呼叫此方法,所以非常適合在使用物件之前做一些初始化工作。note 如果子類中定義了建構函式則不會隱式呼叫其父類的建構函式。要執行父類的建構函式,需要在子類的建構函式中呼叫 parent construct...

PHP 建構函式

class a if array key exists name params if array key exists age params if array key exists params public function getinfo1 public function getinfo2 cl...

前端學習(十一)建構函式的繼承

建構函式間的繼承,如 function animal function pig color,name 想讓pig構造器繼承animal構造器function pig color,name var redpig new pig red zht alert redpig.atr 動物二 prototyp...