PHP 5.3 加上了 get_called_class() 這個 function,使得 Rails 上面的 ActiveRecord 在 PHP 的實作成為可行。過去的 PHP 假如遇到了


class Foo
{
public static function bar(){
// ...
}
}

class FooA extends Foo
{
}



這樣子的 code ,在 5.2 以前用 Foo::bar(); 和 FooA::bar(); 是完全無法分辨 bar() 是被 Foo 還是被 FooA 呼叫的。
因此像是 ActiveRecord 的 User::search(1), Comment::find(2) 這種寫法,在 PHP 5.2 完全作不到,除非在 extends 之後還要再自己 implements 一次 find, search 這些 method。

但是 PHP 5.3 增加了 get_called_class() 之後讓一切變的可行了。

我可以在 bar() 裡面呼叫 echo get_called_class()
這樣子 Foo::bar(); 時會印出 Foo, FooA::bar(); 時會印出 FooA
等於我就可以抓出是哪一個 class 呼叫這個 method 了。

而 PHP 5.3 也增加了 __callStatic() 這個 magic method,讓 Foo::any_method() 也可以被使用
使得 PHP 5.3 的彈性大大的增加了。

不過今天在寫 PHP 5.3 程式時,倒是遇到一個靈異現象。


class Test
{
public function test()
{
Foo::bar();
}
}

class Foo
{
public function bar()
{
echo get_called_class();
var_dump($this);
}
}

$test = new Test();



本來預期 echo 的應該是 Foo 這個 class ,沒想到卻出來的是出人意料的 Test 這個 class 。
連下面的 var_dump($this) 都是顯示 Test Object 。

查了一下才知道,在這邊 static 這個 keyword 就很重要了。
如果改成 public static function bar() ,一切就有如預期了
echo 出的 class name 是 Foo ,而且下面 var_dump($this) 是印出 NULL 。

所以使用上要注意,有使用 get_called_class() 的 function ,一定要是 static function ,不然很容易遇到靈異現象。(其實 PHP document 上也寫了這個 function 功用是 「Gets the name of the class the static method is called in. 」,如果不加上 static 造成錯誤的確也是 programmer 的問題啊。

每次看到靈異現象都會讓我想起一句很有道理的話,「程式不會照你所想的跑,只會照你所寫的跑。」


arrow
arrow
    全站熱搜

    榮尼王 發表在 痞客邦 留言(0) 人氣()