PHP OOP - တည်ဆောက်သူ
PHP - __construct Function
တည်ဆောက်မှုတစ်ခုသည် အရာဝတ္ထုတစ်ခုကို ဖန်တီးသည့်အခါတွင် အရာဝတ္ထုတစ်ခု၏ ဂုဏ်သတ္တိများကို စတင်ခွင့်ပြုသည်။
သင် __construct()
function တစ်ခုကို ဖန်တီးပါက၊ သင် class တစ်ခုမှ object တစ်ခုကို ဖန်တီးသောအခါ PHP သည် ဤ function ကို အလိုအလျောက် ခေါ်ပါမည်။
construct function သည် underscore နှစ်ခု (__) ဖြင့် စတင်သည်ကို သတိပြုပါ။
constructor ကိုအသုံးပြုခြင်းဖြင့် code ပမာဏကိုလျှော့ချပေးသည့် set_name() method ကိုခေါ်ဆိုခြင်းမှ ကျွန်ုပ်တို့ကို ကယ်တင်ကြောင်း အောက်ပါဥပမာတွင် ကျွန်ုပ်တို့တွေ့မြင်ရသည်-
ဥပမာ
<?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();
?>