我正试图访问函数中类内的变量:
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;
有很多方法可以做到这一点没有人提到静态关键字
你可以在课堂上做:
static::$api_key
您还可以使用引用和关键字,如parent、self或using类名。
自我和静态是有区别的。当您重写类self::中的静态变量时,它将指向调用它的类,而static::do更明智,并将检查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
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
}