【发布时间】:2014-04-13 05:48:30
【问题描述】:
如何在事先不知道需要传递多少个参数给 call_user_func 的情况下动态构建参数数组:
作为一个简单的例子,假设我试图调用的函数如下:
class foo {
// Param 1 must be boolean,
// Param 2 must be array(),
// Param 3 is string
function bar($param1, $param2, $param3) {
if($param1 == true) {
foeach($param2 as $pvalue) {
echo $param3 . ' - ' . $pvalue;
}
}
}
}
我使用我编写的类来调用它(我需要帮助的类中的内联 cmets)
$event = new event('foo');
// Params to Pass
$array = Array(1,2,3);
$bool = true;
$string = 'Number: ';
$event::AddParam($bool);
$event::AddParam($array);
$event::AddParam($string);
$event::RaiseEvent('bar');
使用我编写的以下类(基本上它是为了模仿事件——所以我相信这是实现 100% 所需的最后一件事),
<?php
/**
* Copyright (C) {2014} {MicroVB INC}
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* unitrack-invoices
* event.php
* 4/13/14 1:11 AM
*
*/
class event {
private static $class;
private static $obj;
private static $params;
public static function init($class=false) {
self::$class = $class;
if($class) {
if(class_exists($class)) {
self:$obj = new $class();
}
}
self::$params = Array();
}
public static function AddParam($value) {
self::$params[] = $value;
}
public static function RaiseEvent($function) {
if(self::$class) {
if(method_exists(self::$obj, $function)) {
foreach(self::$params as $param) {
// Build each $param into something passable to call_user_func_array
// Please note that each item in this array could be an array as well
}
call_user_func_array(Array(self::$obj, $function), $paramlist );
self::$params = Array();
} else {
// Method does not exist - throw error;
}
} else {
if(function_exists($function)) {
foreach(self::$params as $param) {
// Build each $param into something passable to call_user_func_array
// Please note that each item in this array could be an array as well
}
call_user_func_array(Array(self::$obj, $function), $paramlist );
self::$params = Array();
} else {
// Function does not exist - throw error;
}
}
}
}
具体来说,我遇到的问题就在这里>>
foreach(self::$params as $param) {
// Build each $param into something passable to call_user_func_array
// Please note that each item in this array could be an array as well
}
call_user_func_array(Array(self::$obj, $function), $paramlist );
我怎样才能使值$paramlist -- 或任何在这里可行的东西。请记住,如果我传递一个数组,它只会导致它是 $param1 为 foo::bar() ...所以我需要能够将它动态分解为 $param1、$param2、$param3 .. . etc ... 不知道foo::bar() 之前有多少参数(也就是说,我不能事先静态分配值)
【问题讨论】:
标签: php events parameter-passing