Thursday, August 16, 2012

visibility method of php


class method ေတြကို public,private,protected သံုးျပီး define လုပ္နုိင္ပါတယ္
ဘာမမေၾကျငာပဲ႔ေရးတဲ႔ method ကေတာ႔ public လို႔သတ္မွတ္နိုင္ပါတယ္

method declaration နမူနာ
<?php
/* MyClass ကိုသတ္မွတ္ */
class MyClass
{
    //public constructor ကိုေၾကျငာ
    public function __construct() {}
   
    //public method ကိုေၾကျငာ
    public function MyPublic() {}
   
    //protected method ကိုေၾကျငာ
    protected function MyProtected() {}
   
    //private method ကိုေၾကျငာ
    private function MyPrivate() {}
   
    //ဒါက public ပါ
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}
$obj = new MyClass;
$obj->MyPublic();              //အလုပ္လုပ္ပါတယ္
$obj->MyProtected();         // Factal Error
$obj->MyPrivate();              // Factal Error
$obj->Foo();                     // Puplic ,Protected,Private အလုပ္လုပ္ပါတယ္

/* OtherClass တစ္ခုကို ထပ္ျပီး သတ္မွတ္ရေအာင္ */
class OtherClass extends MyClass
{   
     // ဒါက public ျဖစ္ပါတယ္
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); //Factal Error
    }
}
$obj2 = new OtherClass();
$obj2->MyPublic(); // အလုပ္လုပ္ပါတယ္
$obj2->Foo2(); // Public ,Protected အလုပ္လုပ္ျပီး Private ကေတာ႔အလုပ္မလုပ္ပါဘူး

class Bar
{   
    public function test()
    {
        $this->testPrivate();
        $this->testPublic();
    }
    public function testPublic()
    {
    echo "Bar::testPublic\n";
    }
    public function testPrivate()
    {
    echo "Bar::testPrivate\n";
    }
}
class Foo extends Bar
{
    public function testPublic()
    {
        echo "Foo::testPublic\n";
    }
    private function testPrivate()
    {
        echo "Foo::testPrivate\n";
    }
}
$FooObj = new Foo();
$FooObj->test();
?>

Visibilityy From other Objects
တူညီတဲ႔ Objects ေတြက အျခား private,protected member ေတြဆီက access လုပ္နိုင္ပါတယ္
ဘာေၾကာင္႔လဲဆိုေတာ႔ ဒီ objects ထဲမွာ detail သတ္မွတ္ထားတဲ႔ ဟာကို အလိုလိုသိလိုပါပဲ႔
တူညီတဲ႔ object type ရဲ႕ private members ကို access လုပ္ၾကည္႔ျခင္း
<?php
class Test
{
    private $foo;
    public function __construct($foo)
    {
        $this->foo  = $foo;
    }
   
    private function bar()
    {
        echo 'Accessed the private method';
    }
   
    public function baz(Test $other)
    {
        //private property ကိုခ်ိန္းနိုင္ပါတယ္
        $other->foo = 'hell0';
        var_dump($other->foo);
       
        //private method ကိုျပန္ေခၚသံုးနိုင္ပါတယ္
        $other->bar();
    }
}
$test =new Test('test');
$test->baz(new Test('other'));
?>

The output is
string(5) 'hell0'
Accessed the private method

No comments:

Post a Comment

Thanks for your comments
Welcome from cyberoot