【问题标题】:What is the differece between private and protected in OOP?OOP 中 private 和 protected 有什么区别?
【发布时间】:2017-05-29 13:57:30
【问题描述】:

我不明白面向对象的 PHP 中私有方法和受保护方法有什么区别。在将方法设为私有后,我可以从扩展类访问它。请检查下面的代码 -

<?php

class person{

private function namedilam(){

    return "likhlam";

}

public function kicu(){

    return $this->namedilam();

}

}

class second extends person{

}

$info = new second;

echo $info->kicu();

【问题讨论】:

标签: php oop private protected


【解决方案1】:

当你这样做时,区别会变得很明显:

class Liam {
    private getFirstName() {
         return "Liam";
    }

    public function getName() {
        return $this->getFirstName();
    }
}

class Max extends Liam {
    private function getFirstName() {
         return "Max";
    }
}

class Peter extends Liam {
    public function getLiamsName() {
        return $this->getFirstName();
    }
}

$max = new Max();
echo $max->getName();
// returns "Liam", not "Max" as you might expect

$peter = new Peter();
echo $peter->getLiamsName();
// PHP Fatal error:  Uncaught Error: Call to private method Liam::getFirstName() [...]

Max 将返回“Liam”,因为 getName() 在 Liam 类中调用 getFirstName(),而不是从扩展它的类中调用。这意味着使用私有方法,您可以确保无论何时在您的类中调用此方法时,都会使用该方法,并且永远不会被覆盖。

笼统地解释一下:

私有方法只能在类内部访问。它们不能被覆盖或从外部甚至是扩展它的类访问。

在类中可以访问受保护的方法在扩展类中,但是你不能像这样从外部调用它们:

$max = new Max();
$max->iAmProtected();

这不适用于私有或受保护的方法。

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2017-09-14
    • 1970-01-01
    • 2020-04-25
    • 2015-07-28
    相关资源
    最近更新 更多