靜態(tài)變量
最基本的知識
function test()
{
static $a = 0;
echo $a;
$a++;
}
/**
如果沒有 static 關鍵字种冬,在第一次運行完 test 函數的時候,$a 就被銷毀了舔糖。
第二次運行函數時候娱两,會被重新賦值為 0 。
存在 static 關鍵字金吗,第一次運行完函數十兢,$a 的值并不會被銷毀。
第二次運行函數的時候辽聊,會去內存 static 區(qū)域中查找 $a 是否存在纪挎,存在就不再賦值了期贫。
*/
連續(xù)聲明會報錯
<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
后期靜態(tài)綁定
<?php
class a{
static protected $test="class a";
public function static_test(){
echo static::$test; // Results class b
echo self::$test; // Results class a
}
}
class b extends a{
static protected $test="class b";
}
$obj = new b();
$obj->static_test();
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who(); // A
static::who(); // B
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
理解繼承
<?php
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test(); // success success
$c = new C();
$c->test(); // success 不能再 A 中訪問 C 的私有方法
復雜的例子
<?php
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}
C::test();
// 輸出 ACC
// 總結跟匆,無論在靜態(tài)綁定前調用的是 self,parent通砍,還是什么亂七八糟的玛臂,最終返回的都是一開始調用的 類。