PHP中的construct函數是一個特殊的方法,用于在實例化一個類的時候自動調用,用來初始化對象。它有以下幾種用法:
class MyClass {
public function __construct() {
echo 'Object has been initialized';
}
}
$obj = new MyClass(); // 輸出:Object has been initialized
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
echo 'Hello, my name is ' . $this->name;
}
}
$person = new Person('Alice'); // 輸出:Hello, my name is Alice
class ParentClass {
public function __construct() {
echo 'Parent class initialized';
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
echo 'Child class initialized';
}
}
$obj = new ChildClass(); // 輸出:Parent class initializedChild class initialized
class Person {
public $name;
public function __construct($name = 'Unknown') {
$this->name = $name;
echo 'Hello, my name is ' . $this->name;
}
}
$person1 = new Person(); // 輸出:Hello, my name is Unknown
$person2 = new Person('Bob'); // 輸出:Hello, my name is Bob