Php 访问私有属性期间的奇怪行为

Php 访问私有属性期间的奇怪行为,php,design-patterns,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::$insta

我写了《下一个单身汉》

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'添加到private属性val.中,并看到'hello'而不是'he',为什么我可以访问private方法?

如果对于整个类访问private scope。它不受私有/受保护/公共方法的限制。因此,您可以从类内访问任何私有成员,但不能从类外访问

  • private当您希望您的变量/函数仅在其自己的类中可见时
  • 受保护的作用域,当您希望使变量/函数在扩展当前类(包括父类)的所有类中可见时
  • public作用域,使该变量/函数可从对象的任何位置、其他类和实例使用
您可以从中阅读详细信息


您会问,为什么允许从静态
getInstance()
修改私有属性
$instance->val
?如果没有私有方法,您可以在哪里访问“私有方法”?@Michael Berkowski,是的,因为它是从内部访问的,而不是从外部访问的,所以允许修改它。尝试
Singleton::getInstance()->val.='llo'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