PHP OOP - Static Methods
PHP - Static Methods
အတန်း၏ဥပမာကို ဦးစွာမဖန်တီးဘဲ Static method များကို တိုက်ရိုက်ခေါ်နိုင်သည်။
တည်ဆဲနည်းလမ်းများကို static
သော့ချက်စာလုံးဖြင့် ကြေငြာသည်-
အထားအသို
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
static method ကိုဝင်ရောက်ရန် class name၊ double colon (::) နှင့် method name ကိုသုံးပါ-
အထားအသို
ClassName::staticMethod();
ဥပမာတစ်ခုကိုကြည့်ရအောင်။
ဥပမာ
<?php
class
greeting {
public static function
welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
နမူနာရှင်းပြထားပါတယ်။
ဤတွင်၊ ကျွန်ုပ်တို့သည် static method ကိုကြေငြာသည်- welcome()။ ထို့နောက်၊ class name၊ double colon (::) နှင့် method name ( class ၏ instance ကိုအရင်ဖန်တီးခြင်းမပြုဘဲ) ကိုအသုံးပြု၍ static method ကိုခေါ်သည်။
PHP - Static Methods တွင် နောက်ထပ်
class တစ်ခုတွင် static နှင့် non-static method နှစ်မျိုးလုံးရှိနိုင်သည်။ self
သော့ချက်စာလုံးနှင့် ကော်လံနှစ်ထပ် (::) ကို အသုံးပြု၍ တူညီသောအတန်းရှိ နည်းလမ်းတစ်ခုမှ တည်ငြိမ်နည်းလမ်းကို ဝင်ရောက်ကြည့်ရှုနိုင်သည် ။
ဥပမာ
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct()
{
self::welcome();
}
}
new
greeting();
?>
Static Method များကို အခြားသော Class များရှိ Method များမှလည်း ခေါ်ဆိုနိုင်ပါသည်။ ဒါကိုလုပ်ဖို့၊ static method ဖြစ်သင့်တယ် public
။
ဥပမာ
<?php
class
greeting {
public static function
welcome() {
echo "Hello World!";
}
}
class
SomeOtherClass {
public function
message() {
greeting::welcome();
}
}
?>
ကလေးအတန်းမှ static method ကိုခေါ်ရန်၊ ကလေးအတန်း parent
အတွင်းရှိသော့ချက်စာလုံးကိုသုံးပါ။ ဤတွင်၊ တည်ငြိမ်နည်းလမ်းသည် public
သို့မဟုတ် protected
ဖြစ်နိုင်သည်။
ဥပမာ
<?php
class domain {
protected static function
getWebsiteName() {
return "W3Schools.com";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName =
parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>