我知道可以使用call_user_func_array()调用一个带有可变数量参数的函数 - > http://php.net/manual/en/function.call-user-func-array.php.我想要做的几乎是相同的,但我想要在它的构造函数中调用一个带有可变数量参数的PHP类,而不是函数.
它会像下面这样工作,但我不知道参数的数量,所以我不知道如何实例化该类.
Run Code Online (Sandbox Code Playgroud)<?php //The class name will be pulled dynamically from another source $myClass = '\Some\Dynamically\Generated\Class'; //The parameters will also be pulled from another source, for simplicity I //have used two parameters. There could be 0, 1, 2, N, ... parameters $myParameters = array ('dynamicparam1', 'dynamicparam2'); //The instantiated class needs to be called with 0, 1, 2, N, ... parameters //not just two parameters. $myClassInstance = new $myClass($myParameters[0], $myParameters[1]);
这是一个基本的网站.根据这里的答案,我这样做:
private $db;
public function __construct($id = null) {
$this->db = Db::getInstance(); //singleton from the Db class
Run Code Online (Sandbox Code Playgroud)
但是如果有静态方法,我就不能使用特定于对象的变量.
有没有什么比在静态方法中手动指定db变量更好的了?
public static function someFunction($theID){
$db = Db::getInstance();
Run Code Online (Sandbox Code Playgroud)
编辑:使变量静态不能解决问题.Access to undeclared static property.我仍然需要在静态函数中分配变量.问题是询问是否有解决方法.
我的数据库类(虽然对此讨论不重要):
class Db {
private static $m_pInstance;
private function __construct() { ... }
public static function getInstance(){
if (!self::$m_pInstance)
self::$m_pInstance = new Db();
return self::$m_pInstance;
}
Run Code Online (Sandbox Code Playgroud)
}