所以我尝试并且可能失败了,写了一个“mixin”类。它大部分都可以正常工作,直到您有一个类传递的多个参数,然后世界崩溃。我的班级是这样的:
class AisisCore_Loader_Mixins {
private $_classes;
private $_class_objects = array();
private $_methods = array();
public function __construct(){
$this->init();
}
public function init(){}
public function setup($class){
if(!is_array($class)){
throw new AisisCore_Loader_LoaderException('Object passed in must be of type $class_name=>$params.');
}
$this->_classes = $class;
$this->get_class_objects();
$this->get_methods();
}
public function get_class_objects(){
foreach($this->_classes as $class_name=>$params){
$object = new ReflectionClass($class_name);
$this->_class_objects[] = $object->newInstance($params);
}
}
public function get_methods(){
foreach($this->_class_objects as $class_object){
$this->_methods = get_class_methods($class_object);
}
}
public function call_function($name, $param = null){
foreach($this->methods as $method){
$this->isParam($method, $param);
}
}
private function isParam($method, $param){
if($param != null){
call_user_func($method, $param);
}else{
call_user_func($method);
}
}
}
并且扩展并在“桥”类中使用:
class AisisCore_Template_Helpers_Loop_LoopMixins extends AisisCore_Loader_Mixins{
private $_options;
private $_wp_query;
private $_post;
private $_components;
public function __construct($options){
parent::__construct();
global $wp_post, $post;
if(isset($options)){
$this->_options = $options;
}
if(null === $wp_query){
$this->_wp_query = $wp_query;
}
if(null === $post){
$this->_post = $post;
}
$this->_components = new AisisCore_Template_Helpers_Loop_LoopComponents($this->_options);
$this->setup(array(
'AisisCore_Template_Helpers_Loop_Helpers_Loops_Single' => array($options, $this->_components),
'AisisCore_Template_Helpers_Loop_Helpers_Loops_Query' => array($options, $this->_components),
'AisisCore_Template_Helpers_Loop_Helpers_Loops_Page' => array($options, $this->_components),
));
}
public function init(){
parent::init();
}
}
问题是什么?
Warning: Missing argument 2 for AisisCore_Template_Helpers_Loop_Helpers_Loops_Single::__construct()
Warning: Missing argument 2 for AisisCore_Template_Helpers_Loop_Helpers_Loops_Query::__construct()
Warning: Missing argument 2 for AisisCore_Template_Helpers_Loop_Helpers_Loops_Page::__construct()
我想做类似的事情:
array($options, $this->_components)
获取该类的参数,将其包装在一个数组中,然后newInstanceArgs
破坏该数组将两个参数放入类中。换句话说,我以为我传递了两个参数??
答案 0 :(得分:4)
错误消息告诉您到底出了什么问题:
Warning: Missing argument 2 for BlahBlahBlah::__construct()
所以问题是当你在这里实例化一个对象时,你的所有参数都没有被传递给构造函数:
$this->_class_objects[] = $object->newInstance($params);
如果您查阅ReflectionClass::newInstance
docs的相关文档,您会看到:
创建该类的新实例。给定的参数传递给 类构造函数。
因此,无论您在$params
数组中有多少元素,您只能使用当前方法将Argument 1传递给构造函数。解决方案是使用ReflectionClass::newInstanceArgs
docs,因为这会扩展参数数组并将它们作为单独的参数传递给构造函数:
$this->_class_objects[] = $object->newInstanceArgs($params);