繁体   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