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