PHP OOP - ตัวสร้าง
PHP - ฟังก์ชัน __construct
ตัวสร้างช่วยให้คุณเริ่มต้นคุณสมบัติของวัตถุเมื่อสร้างวัตถุ
หากคุณสร้าง__construct()
ฟังก์ชัน PHP จะเรียกใช้ฟังก์ชันนี้โดยอัตโนมัติเมื่อคุณสร้างวัตถุจากคลาส
สังเกตว่าฟังก์ชัน construct เริ่มต้นด้วยขีดล่างสองตัว (__)!
เราเห็นในตัวอย่างด้านล่าง การใช้ตัวสร้างช่วยเราจากการเรียกเมธอด 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();
?>