PHP 面向对象基础:封装性 protected 2 个改进

被定义为受保护的类成员则可以被其自身以及其子类和父类访问。

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
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 1
class MyTest
{
    //受保护属性
   protected $a = 'protected';

    // 受保护方法
    public function printProtected() //** 这里的public是不是该改成 protected?**//
    {
        echo "Called protected funtion" . "<br />";

    }

    // 类自身调用受保护属性与方法
    public function printEverything()
    {
        echo $this->a . " | ";
        $this->printProtected();
    }
}
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!