PHP访问私有静态变量vs私有变量


PHP accessing private static variables vs private variables?

这可能是一个愚蠢的问题,但直到现在我注意到以下内容:

<?php
    class Something {
        private $another;
        private static $yetAnother;
        public function printSomething($what_to_print){
            $this->another = $what_to_print;
            $this::$yetAnother = $what_to_print;
            //print($this::$yetAnother);//prints good
            //print($this->another); //prints good
            //print($this->$another); //PHP Notice:  Undefined variable:
            //print($this::yetAnother); //PHP Fatal error:  Undefined class constant
        }
    }
    $x = new Something();
    $x->printSomething("Hello World!");
?>

为什么我可以使用$访问静态变量,但如果我不使用系统将其理解为const..但我不能很好地理解它。只是为了语法?还是有其他原因?

静态变量是类属性,而不是对象属性。因此,它们为具有相同值的所有对象共享,并且无需对象就可以使用它们。因此,访问这些属性的正确方法是在类内部使用self::$yetAnother(或static::$yetAnother)或从外部使用Something::$yetAnother(如果是公共的)。"$this->"是对对象的引用,但属性$yetAnother不是对象属性,而是静态类属性,所以你可以通过这种方式访问该属性(php在这里没有非常严格的限制),但正确的方式是self::, static::或classname::。

由于变量需要$作为前缀,因此不能通过$this::yetAnother或self::yetAnother访问它,因为这将是const的名称。这就是为什么$this::yetAnother会给你一个错误,因为没有该名称的const