我试图在函数中访问类中的变量:
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
}
Run Code Online (Sandbox Code Playgroud)
有很多方法可以做到没有人提到静态关键字
你可以在课堂上做:
static::$api_key
Run Code Online (Sandbox Code Playgroud)
您还可以使用引用和关键字,如 parent、self 或 using class name。
self 和 static 之间存在差异。当你在类 self:: 中覆盖静态变量时,它会指向它被调用的类,而 static:: 确实更聪明,并且会检查 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();
Run Code Online (Sandbox Code Playgroud)
输出:
class b
class a
class a
class b
Run Code Online (Sandbox Code Playgroud)
更多关于:
http://php.net/manual/pl/language.oop5.static.php
| 归档时间: |
|
| 查看次数: |
6962 次 |
| 最近记录: |