Private, Protected in PHP

Public là phương thức. Dùng từ khóa này có thể gọi ở bất kể đâu
Private là phương thức : Chi có thể gọi nó trong class chứa nó
Protected là phương thức : có thể được gọi trong class chứa nó và class kế thừa.

VD Protected:

<?php
class MyClass
{
    public $prop1="I'm a class property!";

    protected function getProperty()
    {
        return $this->prop1."<br>";
    }
}

class MyOtherClass extends MyClass
{
    
    public function callProtected()
    {
        return $this->getProperty();
        
    }
}
$obj=new MyOtherClass;
echo $obj->callProtected();//đúng
?>
Kết quả:I'm a class property!


VD Private:
<?php
class MyClass
{
    public $prop1="I'm a class property!";

    private function getProperty()
    {
        return $this->prop1."<br>";
    }
}

class MyOtherClass extends MyClass
{
    
    public function callProtected()
    {
        return $this->getProperty();
        
    }
}
$obj=new MyOtherClass;
echo $obj->callProtected();//Sai
?>

Kết quả: Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass' in C:\AppServ\www\oop\test\test.php on line 43