访问私有属性时出现奇怪的行为

时间:2014-01-23 17:10:15

标签: php design-patterns

我写了下一个单身人士。

class Singleton {
    // object instance
    private static $instance;

    private function __construct() {}

    private function __clone() {}
    private $val = 'he';

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
            self::$instance->val .= 'llo';
        }
        return self::$instance;
    }

    public function doAction() {
       echo $this->val;
    }
}
Singleton::getInstance()->doAction();

当我得到它的实例时,我将'llo'添加到私有属性val。并看到'你好'而不是'他',为什么我可以访问私有方法?

1 个答案:

答案 0 :(得分:1)

如果是全班,则访问私人范围。它不受私人/受保护/公共方法的限制。因此,您可以从班级内部访问任何私人成员,但不能从班级外部访问。

  • 私有范围当您希望变量/函数仅在其自己的类中可见时。
  • protected 范围,如果要在扩展当前类(包括父类)的所有类中显示变量/函数。
  • 公开范围,可以从对象的任何位置,其他类和实例中获取该变量/函数。

您可以阅读http://php.net/manual/en/language.oop5.visibility.php

中的详细信息
class Singleton {
  // object instance
  private static $instance;

  private function __construct() {}

  private function __clone() {}
  private $val = 'he';

  public static function getInstance() {
    if (self::$instance === null) {
        self::$instance = new Singleton();
        self::$instance->val .= 'llo'; // Inside the same class you can access private variable
    }
    return self::$instance;
  }

  public function doAction() {
   echo $this->val;
  }
}
Singleton::getInstance()->doAction();
echo Singleton::getInstance()->val; // can't access