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

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.

<?php

class 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:

<?php

class 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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值