PHP 面向对象基础:封装性 protected
被定义为受保护的类成员则可以被其自身以及其子类和父类访问。
class MyTest
{
//受保护属性
protected $a = 'protected';
// 受保护方法
public function printProtected()
{
echo "Called protected funtion" . "<br />";
}
// 类自身调用受保护属性与方法
public function printEverything()
{
echo $this->a . " | ";
$this->printProtected();
}
}
受保护属性和方法不能被对象直接调用,但类自身可以调用
$test = new MyTest();
echo $test->a . "<br />";
// Fatal error: Uncaught Error: Cannot access protected property MyTest::$a
$test->printProtected();
// Fatal error: Uncaught Error: Call to protected method MyTest::printProtected()
// 类自身可以调用
$test->printEverything(); // protected | Called protected funtion
子类可以调用父类受保护属性和方法
class Test extends MyTest
{
public function printProtected()
{
// 调用父类受保护属性和方法
echo $this->a . " | ";
parent::printProtected();
}
}
$obj = new Test();
$obj->printProtected(); // protected | Called protected funtion
父类也可以调用子类的受保护属性和方法
class OtherTest extends MyTest
{
public function printProtected()
{
// 调用子类受保护属性和方法
$anotherTest = new AnotherTest();
echo $anotherTest->b . ' | ';
echo $anotherTest->callProtected();
}
}
class AnotherTest extends OtherTest
{
protected $b = 'protected of child';
protected function callProtected()
{
echo 'Called protected function in child class';
}
}
$test = new OtherTest();
$test->printProtected(); // protected of child | Called protected function in child class