no, I meant more like this:
PHP Code:
abstract class abstractWidget extends Factory {
protected function __construct($args){
$this->args = $args;
}
public function returnParamsAndArgs(){
return parent::$params . "<br />" . $this->args;
}
public static function makeWidget($args){
throw new Exception("Cannot use Widget class to create widgets.");
}
}
then, every Widget-esque class extends from abstractWidget:
PHP Code:
class Widget extends abstractWidget {
}
class Wodget extends abstractWidget {
}
class Wudget extends abstractWidget {
}
alternatively, you could use debug_backtrace() to figure out what class (if any) is trying to create the object, and fail if it isn't the object you expected. Widget would ideally be abstract in this case, too, and all widgets would extend the base Widget class so that they have the same constructor. instead of changing the constructor, have an initialization method. example:
PHP Code:
<?php
class Factory{
protected static $params;
private function __construct(){}
public static function setParams($params){
self::$params = $params;
}
public static function getParams(){
return self::$params;
}
public static function makeWidget($args){
return new Widget($args);
}
}
abstract class abstractWidget {
protected $args;
final public function __construct(){
$debug = debug_backtrace();
if(!isset($debug[1]['class']) || $debug[1]['class'] != "Factory"){
throw new Exception("Widgets must be created using the Factory class.");
}
// pass all parameters pass to the constructor to the initialization function
call_user_func_array(array($this, 'init'), func_get_args());
}
final public function returnParamsAndArgs(){
return Factory::getParams() . "\n" . $this->args . "\n";
}
// initialization function must be implemented
abstract protected function init();
}
class Widget extends abstractWidget {
// no need for a constructor, just the initialization function:
protected function init(){
$args = func_get_arg(0); // this could be annoying, though
$this->args = $args;
}
}
header("Content-Type: text/plain");
try {
Factory::setParams("foo");
echo Factory::makeWidget("bar")->returnParamsAndArgs();
new Widget('testing');
}catch(Exception $e){
echo $e->getMessage();
}
?>