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?
Although you call
parent::singleton()fromsubclass, but thesingleton()still creates you instance ofbaseclass (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
baseclass, 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.