我想为框架提供的类型添加一些功能,但是这个类型是singleton
。
singleton
,但我不知道如何初始化它。我不能修改原类的代码。
现在我不扩展,只是保持一个私有属性,在我的getInstance
中初始化,并使用__call(),但它是不够的,不直观的使用。
您需要将扩展类中的构造函数保持为私有。但是,您可以执行以下操作:
class originalClass
{
private function __construct()
{
/* Do something */
}
public static function init()
{
self::__construct();
}
}
class extendedClass extends originalClass
{
private function __construct()
{
parent::init();
}
public static function init()
{
self::__construct();
}
}
$var = extendedClass::init();
或者,你可以选择让你的类作为一个独立的,并使用一个神奇的方法来访问"父"对象:
class pdoExtender
{
private $someProperty;
public function __construct()
{
$this->someProperty = new PDO(...);
}
public function __call($name, $args)
{
if(method_exists(array($this, $someProperty), $name))
{
return call_user_func_array(array($this, $someProperty), $args);
}
}
}
// Example function calls:
$db = new pdoExtender;
// As (obj)pdoExtender doesn't have the method 'prepare()', the __call() method is invoked to check the 'parent' object, PDO
$db->prepare();