函式名稱:DocResult::__construct()
版本要求:PHP 5+
函式描述:建構函式,當一個物件被建立時自動呼叫。可用於對物件的屬性進行初始化或執行其他必要的操作。
語法:public __construct ( [ mixed $arg1 [, $arg2 [, $... ]]] )
引數:
- arg1, arg2, ...:可選引數,用於在物件建立時傳遞給建構函式的引數。數量和型別根據具體情況而定。
示例:
class DocResult {
public $result;
// 建構函式
public function __construct($result) {
$this->result = $result;
echo "物件已建立,結果為:" . $this->result . PHP_EOL;
}
public function getResult() {
return $this->result;
}
}
// 建立物件,並傳遞引數
$resultObj = new DocResult("Hello World");
// 訪問物件的屬性和方法
echo $resultObj->getResult() . PHP_EOL;
輸出:
物件已建立,結果為:Hello World
Hello World
備註:
- 建構函式的名稱必須為
__construct
,並且在建立物件時會自動呼叫。 - 建構函式可以接受任意數量的引數,根據需求進行定義和使用。
- 在示例中,建構函式接受一個引數
$result
,並將其賦值給物件的屬性$result
。在建構函式內部,可以執行任意其他必要操作。