非静态调用静态方法 [英] Calling static method non-statically

查看:69
本文介绍了非静态调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个子类,该子类仅使用静态方法扩展了一个类.我想使此子类成为单例而不是静态的,因为原始开发人员确实想要单例,但改用了静态的(显而易见,因为静态类中的每个方法都调用Init()函数(基本上是构造函数)).

父级中的大多数方法不需要在子级中被覆盖,但是我想避免不得不编写这样的方法:

public function Load($id)
{
     return parent::Load($id);
}

当我不想完全覆盖该方法而只使用:

$child->Load($id);

是否可以非静态地调用静态方法?是否可以使用实例对象扩展静态对象?我知道我可以尝试一下,并且可能会起作用(PHP非常宽容),但是我不知道是否有任何我需要关注的事情.

解决方案

  • 您可以继承静态方法吗?

  • 您可以覆盖静态方法吗?

是的,但是只有从PHP 5.3开始,它们才能像您期望的那样工作: 解决方案

Yes

  • Can you override static methods?

Yes, but only as of PHP 5.3 do they work as you would expect: http://www.php.net/manual/en/language.oop5.static.php (ie. self binds to the actual class and not the class it's defined in).

  • Is it possible to call a static method non-statically?

Yes, but will lose $this. You don't get a warning (yet) but there also isn't really a reason to call it the wrong way.

这篇关于非静态调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆