在函数php中访问类中的公共静态变量

时间:2014-09-04 09:16:38

标签: php class oop

我试图在函数中访问类中的变量:

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
}

3 个答案:

答案 0 :(得分:8)

使用值/方法(包括静态的)内部类的通用方法是self::

echo self::$api_key;

答案 1 :(得分:3)

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
}

答案 2 :(得分:3)

有很多方法可以做到没有人提到静态关键字

你可以在课堂上做:

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