簡體   English   中英

在函數php中訪問類中的公共靜態變量

[英]Access public static variable inside class in function php

我試圖在函數中訪問類中的變量:

class google_api_v3 {

  public static $api_key = 'this is a string';

  function send_response() {
     // access here $api_key, I tried with $this->api_key, but that works only on private and that variable I need also to access it outside the class that is why I need it public.
  }

}

function outside_class() {
  $object = new google_api_v3;
  // works accessing it with $object::api_key
}

使用值一個通用的方法/在類的方法(包括靜態的)是self::

echo self::$api_key;
class google_api_v3 {

  public static $api_key = 'this is a string';

  function send_response() {
     $key = google_api_v3::$api_key
  }

}

function outside_class() {
  $object = new google_api_v3;
  // works accessing it with $object::api_key
}

有很多方法可以做到沒有人提到靜態關鍵字

你可以在課堂上做:

static::$api_key

您還可以使用父,自我或使用類名等引用和關鍵字。

自我和靜態之間存在差異。 當你在類中重寫靜態變量時,self ::將指向調用它的類,static :: does更加明智,並將檢查ovverides。 有一些來自php.net的例子寫在評論中我已經修改了一點只是為了顯示差異。

<?php

abstract class a
{
    static protected $test="class a";

    public function static_test()
    {
        echo static::$test; // Results class b
        echo self::$test; // Results class a
        echo a::$test; // Results class a
        echo b::$test; // Results class b
    }

}

class b extends a
{
    static protected $test="class b";
}

$obj = new b();
$obj->static_test();

輸出:

class b
class a
class a
class b

更多關於:

http://php.net/manual/pl/language.oop5.static.php

暫無
暫無

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

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