Developer အမ်ားစုက PHP scource class တစ္ခုစီရဲ႕ definition နဲ႔ object-oriented applications ေတြေရးလာၾကပါတယ္
class တစ္ခုစီ၏ အစမွာ ပါတဲ႔ ရွည္းလ်ားလွတဲ႔ list ေတြကိုေရးဖို႔ အဓိက class ကိုေၾကျငာေပးရပါတယ္
PHP 5 မွာဆိုရင္ေတာ႔ သိပ္ျပီး မလိုအပ္ပါဘူး autoload() function ကို define လုပ္နိုင္ပါတယ္ အဲဒါက
ကၽြန္ေတာ္တို႔ define မလုပ္ရေသးတဲ႔ class or interface ကိုအသံုးျပဳဖို႔ အတြက္ automatically ေခၚသံုးတဲ႔ function တစ္ခုျဖစ္ပါတယ္
ဒီ function ကိုေခၚသံုးျခင္းျဖင္႔ scripting engine က PHP ရဲ႕ error မျဖစ္ခင္ class ကို load လုပ္ဖို႔အတြက္ ေနာက္ဆံုးအခြင္႔ေရးကိုေပးလိုက္တာပါ
Note: PHP 5.3 အထက္ဆိုရင္ __autoload function မွာရွိတဲ႔ exception thrown function က catch block ထဲ႔မွာမဖမ္းနိုင္ပါဘူး
ျပီးေတာ႔ fatal error ကို result အျဖစ္ထုတ္ျပေပးမွာပါ
PHP 5.3 မွာဆိုရင္ေတာ႔ ဒါကို catch bloack ထဲမွာ ဖမ္းေပးနိုင္ပါတယ္
__autoload function ကို custom exception class ကို autoload ဖို႔ ထပ္တစ္လဲလဲျပန္သံုးနိုင္ပါတယ္
ဥပမာ
<?php
function __autoload($class_name){
include $class_name . ' .php';
}
$obj=new MyClass1();
$obj2=new MyClass2();
?>
အဲဒီ example က MyClass1.php နဲ႔ MyClass2.php အသီးသီရွိတဲ႔ files ေတြကေန MyClass1 နဲ႔ MyClass2 ဆိုတဲ႔ Classes ေတြကို load လုပ္ျပထားတာပါ
ဥပမာေလးတစ္ခု
<?php
function __autoload($name) {
var_dump($name);
}
class Foo implements TestClass{
}
?>
The Output is
string(5) "TestClass"
Fatal error: Interface 'ITest' not found in D:\xampplite\htdocs\php.php on line 7
error တက္မွာပါ ဘာေၾကာင္႔လဲဆိုေတာ႔ TestClass မွာ ကၽြန္ေတာ္တို႔ Nothing function and Method မရွိဘူးေလ
ေနာက္တစ္ခုက Autoloading with exception handling for 5.3.0+
<?php
function __autoload($name) {
echo "Want to load $name.\n";
throw new Exception("Unable to load $name.");
}
try {
$obj = new NonLoadableClass();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
The Output is
Want to load NonLoadableClass.
Fatal error: Class 'NonLoadableClass' not found in D:\xampplite\htdocs\php.php on line 12
အဲဒီမွာ try / catch block ကို throw exception သံုးျပီးလုပ္ျပသြားတာပါ
ေနာက္ထပ္တစ္ခုက Missing custom exception ပဲ႔ျဖစ္ပါတယ္
<?php
function __autoload($name) {
echo "Want to load $name.\n";
throw new MissingException("Unable to load $name.");
}
try {
$obj = new NonLoadableClass();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
The Output is
Want to load NonLoadableClass. Want to load MissingException.
Fatal error: Class 'MissingException' not found in D:\xampplite\htdocs\php.php on line 4
No comments:
Post a Comment
Thanks for your comments
Welcome from cyberoot