PHP 面向对象基础:封装性 private 1 个改进

被定义为私有的类成员则只能被其定义所在的类访问。

class MyTest
{
    // 私有属性
   private $a = 'private';

    // 私有方法
    private function printPrivate()
    {
        echo "Called private funtion" . "<br />";

    }

    // 类自身调用私有属性与方法
    public function printEverything()
    {
        echo $this->a . " | ";
        $this->printPrivate();
    }
}

私有属性和方法不能被对象直接调用,但类自身可以调用

$test = new MyTest();
// 私有属性不可访问 Fatal error: Uncaught Error: Cannot access private property MyTest::$a
echo $test->a . "<br />";
// 私有属性不可获取 Fatal error: Uncaught Error: Call to private method MyTest::printPrivate()
$test->printPrivate();
// 类自身可以调用,打印出 private | Called private funtion
$test->printEverything();

子类不可以调用父类私有属性和方法

class Test extends MyTest
{
    public function printProtected()
    {
        // 调用父类受私有属性和方法
        echo $this->a . " | ";
        parent::printProtected();
    }
}

$obj = new Test();
// 父类私有属性在子类中显示为未定义 Notice: Undefined property: Test::$a
// 父类私有方法不可获取 Fatal error: Uncaught Error: Call to private method MyTest::printPrivate()
$obj->printPrivate();

父类也不可以调用子类私有属性与方法

class OtherTest extends MyTest
{
    public function printPrivateProperty()
    {
        // 调用子类私有属性
        $anotherTest = new AnotherTest();
        echo $anotherTest->b;
    }

    public function printPrivateMethod()
    {
        // 调用子类私有方法
        $anotherTest = new AnotherTest();
        echo $anotherTest->callPrivate();
    }
}

class AnotherTest extends OtherTest
{
    // 子类私有属性
    private $b = 'private of child';
    // 子类私有方法
    private function callPrivate()
    {
        echo 'Called private function in child class';
    }
}

$test = new OtherTest();
// 子类私有属性不可访问 Fatal error: Uncaught Error: Cannot access private property AnotherTest::$b
$test->printPrivateProperty();
// 子类私有方法不可获取 Fatal error: Uncaught Error: Call to private method AnotherTest::callPrivate()
$test->printPrivateMethod();
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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