php oop扩展问题
我有以下课程。
class base {
private function __construct(){
//check if foo method exists
//$this->foo(); // if it exists
}
public static function singleton(){
if(!isset(self::$singleton)){
self::$singleton = new base();
}
return self::$singleton;
}
}
class sub extends base{
public function __construct() {
parent::singleton();
}
public function foo(){
}
}
然后像这样初始化它,
$test = new sub();
我的问题是我想检查 base __construct
子组件是否有 foo
方法。 但好像没有这个方法。
有人可以告诉我我哪里出了问题吗?
i have the following classes.
class base {
private function __construct(){
//check if foo method exists
//$this->foo(); // if it exists
}
public static function singleton(){
if(!isset(self::$singleton)){
self::$singleton = new base();
}
return self::$singleton;
}
}
class sub extends base{
public function __construct() {
parent::singleton();
}
public function foo(){
}
}
then init it like so
$test = new sub();
my problem is that I want to check on base __construct
if the sub has a foo
method.
but it doesn't seem to have this method.
can someone tell me where have I gone wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然您从
sub
类调用parent::singleton()
,但是singleton()
仍然为您创建base
的实例code> 类(因为您执行了new base()
),它没有您的foo()
方法。一般来说,您不应该使用/调用基类中未定义的任何方法。因为它使您的代码不干净:如果您将实现另一个扩展您的
base
类的类,但忘记实现foo()
方法怎么办?您可能很快就会遇到致命错误...如果您确定,此 foo() 方法将始终由任何子类实现 - 您可以在基类中定义为抽象方法 -那么任何子类都将被迫实现它。或者至少作为同一基类中的空方法......这样您的代码将变得干净且结构化。
Although you call
parent::singleton()
fromsub
class, but thesingleton()
still creates you instance ofbase
class (because you donew base()
), which does not have yourfoo()
method.In general you shouldn't use/call any methods from base class, which aren't define in it. Because it makes your code not clean: what if you will implement some another class which extends your
base
class, but forgets to implement thefoo()
method? You can end up with fatal errors quite fast...If you are sure, that this
foo()
method will be always implemented by any child class - you can define in as abstract method in base class - then any child class will be forced to implement it. Or at least as an empty method in the same base class... This way your code will be clean and structured.方法
foo
将不存在,因为正在创建的单例是base
的实例。正在发生的事情是这样的:sub
的实例sub
的构造函数获取单例实例。singleton()
创建base
的实例base
构造函数检查base
类是否包含名为 foo 的方法。事实并非如此。编辑
在这种情况下,单例模式是多余的。相反,您可以从实现所需前端控制器模式的基本工厂类开始:
The method
foo
will not exist as the singleton being creating is an instance ofbase
. Here's what's happening:sub
sub
gets the singleton instance.singleton()
creates an instance ofbase
base
constructor checks if thebase
class contains a method named foo. It does not.Edit
In this case the singleton pattern is superfluous. Instead, you can start with a basic factory class that implements the desired front controller pattern: