PHP:类扩展问题“从上下文调用私有方法...”
我在 WordPress 中有 3 个类(问题本身与它无关):
class WP_Widget
class Theme_Widget extends WP_Widget
class Specific_Widget extends Theme_Widget
本质上 Theme_Widget 包含基本 WP_Widget 的一些扩展功能。
在 Specific_Widget 内部,我调用 Theme_Widget 的方法之一:
class Specific_Widget {
function __construct() {
$this->some_method_that_belongs_to_Theme_Widget();
}
}
当我实例化 Specific_Widget 时,PHP 抛出一个致命错误,如下所示:
Fatal error: Call to private method Theme_Widget::some_method_that_belongs_to_Theme_Widget() from context 'Specific_Widget' in ...
你知道如何解决这个问题吗?这是我第一次从 PHP 收到此错误。它可能源自 WordPress 本身吗?
I have 3 classes in WordPress (the question itself is unrelated to it):
class WP_Widget
class Theme_Widget extends WP_Widget
class Specific_Widget extends Theme_Widget
Essentially Theme_Widget contains some extension functions to the basic WP_Widget.
Inside Specific_Widget I call one of Theme_Widget's methods:
class Specific_Widget {
function __construct() {
$this->some_method_that_belongs_to_Theme_Widget();
}
}
When I instantiate Specific_Widget, PHP throws a fatal error as follows:
Fatal error: Call to private method Theme_Widget::some_method_that_belongs_to_Theme_Widget() from context 'Specific_Widget' in ...
Do you have an idea as to how I can resolve this? This is the first time I've received this error from PHP. Could it be derive from WordPress itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望子类能够使用您的方法,则必须将其声明为
protected
,而不是private
。You must declare your method
protected
, rather thanprivate
, if you wish child classes to be able to use it.如果您想从扩展类访问子函数而不在 URL 中传递受保护函数,请使用受保护函数
例如,
use
protected function
if you would to access a child functions from your extended class's without passing the protected function in URLsfor example