Unexpected Result from Calling a Non-static Function with class::method()

来源:互联网 发布:怎么进入淘宝店铺 编辑:程序博客网 时间:2024/06/03 13:20

The static keyword, which does not exist in PHP 4, is imported since PHP 5. And there's also a new usage (PHP 5.3) static::method(), which enables a method derived from a parent class to call methods or access constants in an object of a derived class.

It's known that non-static methods can be called with the syntax class::method(), just like a static function. But weird result may come. The problem I came across this morning was as follows.

<?phpclass A{public function GetTableName(){return static::NAME;}}class B extends A{const NAME = 'B';}class C{const NAME = 'C';public function getBTableName(){return B::GetTableName();}}$c = new C();echo $c->getBTableName();?>

I expected the output should be B. Unfortunately, it was C. I've tried several possible solutions and it worked when I made A::GetTableName() static.

The solution:

<?phpclass A{static public function GetTableName(){return static::NAME;}}class B extends A{const NAME = 'B';}class C{const NAME = 'C';public function getBTableName(){return B::GetTableName();}}$c = new C();echo $c->getBTableName();?>

I thought a non-static method works just as it's static if called with class::method(), the way a static one is called. And PHP allows that. But they can't work exactly the same.

static::NAME is actually C::NAME, though class C is not derived from class A, when non-static B::GetTableName() is called statically inside class C.

static::NAME will still be B::NAME when static B::GetTableName() is called.

Non-static methods doesn't always act like static ones any more, if called with class::method().

That's what I draw. Possibly wrong~ Syntax of PHP is what I have been learning for years but don't really understand.

原创粉丝点击