PHP တွင် OOP နည်းလမ်းများကို ကိုယ်ပိုင်အသုံးပြုနည်း
ပိုင်ဆိုင်မှုများသာမက နည်းလမ်းများကိုလည်း ကိုယ်ပိုင်အဖြစ် သတ်မှတ်နိုင်ပါသည်။ ပုံမှန်အားဖြင့် ကူညီပေးသော နည်းလမ်းများကို ၎င်းတို့သည် အတန်းပြင်ပမှ မတော်တဆခေါ်ယူခြင်းမခံရစေရန် ကိုယ်ပိုင်အဖြစ် ပြုလုပ်ကြသည်။
ဥပမာတစ်ခုဖြင့် ကြည့်ရအောင်။ ကျွန်ုပ်တို့တွင် အောက်ပါအတန်းရှိသည်ဟု ဆိုကြပါစို့:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->name;
}
}
?>
ဤအတန်းတွင် ကိုယ်ပိုင်နည်းလမ်းတစ်ခုကို ပြုလုပ်ကြပါစို့။ ၎င်းသည် စာသားတစ်ကြောင်းကို လက်ခံပြီး ၎င်း၏ ပထမစာလုံးကို အကြီးစာလုံးပြောင်းပေးမည်:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->name;
}
private function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
ကျွန်ုပ်တို့၏ ကူညီပေးသော နည်းလမ်းကို အခြားနည်းလမ်းတစ်ခုအတွင်း၌ အသုံးပြုကြပါစို့:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->cape($this->name);
}
private function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
စစ်ဆေးကြည့်ကြပါစို့။ ကျွန်ုပ်တို့၏ အတန်းမှ ဝတ္ထုတစ်ခုကို ဖန်တီးကြမည်:
<?php
$user = new User('john');
?>
အများသုံးနည်းလမ်းကို ခေါ်ယူကြမည်။ ကူညီပေးသော နည်းလမ်းကို အသုံးပြုထားသည်:
<?php
echo $user->show();
?>
အောက်ပါကုဒ်တွင် ကူညီပေးသော နည်းလမ်းကို ကိုယ်ပိုင်အဖြစ် ပြောင်းလဲပါ:
<?php
class Employee {
public function __construct($name, $salary) {
$this->name = $name;
$this->salary = $salary;
}
public function getSalary() {
return $this->addSign($this->salary);
}
public function addSign($num) {
return $num . '$
;
}
}
?>