Tuesday, July 17, 2012

php constants

လူအမ်ားစုကေတာ႔ constants ေၾကျငာတဲ႔အခါ ရွဳပ္ေထြးျပီးမွားတတ္ၾကပါတယ္
constants အျဖစ္ေၾကျငာတဲ႔ array သို႔မဟုတ္ function ေတြသံုးတဲ႔အခါမွာေပါ႔
constant ဆိုတာကေတာ႔ တန္ဖိုးတစ္ခုရဲ႕ နာမည္ပါ ( variable မဟုတ္ပါဘူး)
အဲဒါက complied လုပ္တဲ႔အခါ code ထဲမွာ ပံုမွန္အားျဖင္႔ replace လုပ္ပါတယ္
ဒါေၾကာင္႔ function က return ျပန္တဲ႔ values ကို အသံုးျပဳလို႔မရပါဘူး
array ကိုလည္းသံုးလို႔မရပါဘူး ဘာေၾကာင္႔လဲဆိုေတာ႔ const က runtime မွာရွိေနတဲ႔ data structure ျဖစ္ေနလို႔ပါပဲ႔
const ကိုအသံုးျပဳရတဲ႔တစ္ခုတည္းေသာရည္ရြယ္ခ်က္က code ထဲက တန္ဖိုးေတြကို အသံုးျပဳခ်င္လို႔ပါ
ဒါမွလည္း လုပ္ေဆာင္ခ်က္ေတြကို ၾကည္႔စရာမလိုပဲ႔ const ကိုသံုးျပီး တစ္ေနရာမွ တစ္ေနရာကို လြယ္ကူစြာျဖင္႔ replace လုပ္နိင္ပါတယ္
ဥပမာ
<?php
/**
 * Constants that deal only with the database
 */
class DbConstant extends aClassConstant {
    protected $host = 'localhost';
    protected $user = 'user';
    protected $password = 'pass';
    protected $database = 'db';
    protected $time;
    function __construct() {
        $this->time = time() + 1; // dynamic assignment
    }
}
?>
အေပၚက code က constants မဟုတ္ပါဘူး / class ရဲ႕ properties ကိုသံုးျပထားတာပါ
သတိျပဳရမွာက const ဆိုတာက class ရဲ႔ definition ကိုထိန္းခ်ဳပ္လိုက္တဲ႔သေဘာပါ
const ေတာ႔  definition ရဲ႕ static ပါ -> operator နဲ႔ access လုပ္လို႔မရနိုင္ပါဘူး
-> လိုမ်ိဳးသံုးခ်င္ရင္ေတာ႔ object အျဖစ္ new keyword နဲ႔ object ဖန္တီးရပါမယ္
const ရဲ႕ အျခားသက္ေရာက္မွုကေတာ႔ const class တစ္ခုအတြက္ property လိုမ်ိဳး တူညီတဲ႔ တန္ဖိုးကို ျပန္ရနိုင္ပါတယ္
<?php
 class Foo
 {
   const foo = 'bar';
   public $foo = 'foobar';
 
  const bar = 'foo';
   static $bar = 'foobar';
 }
 
var_dump(foo::$bar); // static property
 var_dump(foo::bar);  // class constant
 
$bar = new Foo();
 var_dump($bar->foo); // object property
 var_dump(bar::foo); // class constant
 ?>

No comments:

Post a Comment

Thanks for your comments
Welcome from cyberoot