簡體   English   中英

PHP訪問私有靜態變量還是私有變量?

[英]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: :,靜態::或類名::。

由於變量需要$作為前綴,這就是為什么您不能通過$ this :: yetAnother或self :: yetAnother訪問它的原因,因為這將是const的名稱。 這就是為什么$ this :: yetAnother給您一個錯誤,因為該名稱沒有const。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM