PHP OOP - 建構函式
PHP - __construct 函式
建構函式允許您在建立物件時初始化物件的屬性。
如果您建立了一個 __construct()
函式,PHP 將在您建立類的物件時自動呼叫該函式。
請注意,建構函式以兩個下劃線(__)開頭!
在下面的示例中,您可以看到使用建構函式可以節省呼叫 set_name() 方法的麻煩,從而減少了程式碼量。
示例
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
自己動手試一試 »
另一個例子
示例
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
自己動手試一試 »