实例和静态函数的重新声明
class me {
private $name;
public function __construct($name) { $this->name = $name; }
public function work() {
return "You are working as ". $this->name;
}
public static function work() {
return "You are working anonymously";
}
}
$new = new me();
me::work();
致命错误:无法重新声明 me::work()
问题是,为什么 php 不允许这样的重新声明。有什么解决方法吗?
class me {
private $name;
public function __construct($name) { $this->name = $name; }
public function work() {
return "You are working as ". $this->name;
}
public static function work() {
return "You are working anonymously";
}
}
$new = new me();
me::work();
Fatal error: Cannot redeclare me::work()
the question is, why php does not allow redeclaration like this. Is there any workaround ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,使用魔术方法创建可以解决此问题,尽管我很可能永远不会在生产代码中执行类似的操作:
触发
__call
当在对象范围内调用不可访问的方法时在内部。当在静态范围内调用不可访问的方法时,
__callStatic
在内部触发。There is actually a workaround for this using magic method creation, although I most likely would never do something like this in production code:
__call
is triggered internally when an inaccessible method is called in object scope.__callStatic
is triggered internally when an inaccessible method is called in static scope.我认为你应该这样做:
Here is how I think you should do it instead: