我在谷歌搜索和Stack Overflow上搜索了很多页面,但都找不到一个看起来适合我的情况的解决方案。我正在尝试构建一个使用call_user_func_array动态创建对象的函数,但似乎还有最后一个问题。
我得到的可捕获致命错误是Object of class Product could not be converted to string
(无法将类Product的对象转换为字符串)。当出现此错误时,在日志中我会得到五个这样的警告(每个参数一个):PHP Warning: Missing argument 1 for Product::__construct(),
然后才是可捕获的致命错误。
这是该函数的代码:
public static function SelectAll($class, $table, $sort_field, $sort_order = "ASC")
{
/* First, the function performs a MySQL query using the provided arguments. */
$query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order;
$result = mysql_query($query);
/* Next, the function dynamically gathers the appropriate number and names of properties. */
$num_fields = mysql_num_fields($result);
for($i=0; $i < ($num_fields); $i++)
{
$fetch = mysql_fetch_field($result, $i);
$properties[$i] = $fetch->name;
}
/* Finally, the function produces and returns an array of constructed objects.*/
while($row = mysql_fetch_assoc($result))
{
for($i=0; $i < ($num_fields); $i++)
{
$args[$i] = $row[$properties[$i]];
}
$array[] = call_user_func_array (new $class, $args);
}
return $array;
}
现在,如果我注释掉 call_user_func_array 这一行,并将其替换为以下内容:
$array[] = new $class($args[0],$args[1],$args[2],$args[3],$args[4]);
页面按照预期加载,并填充我正在构建的表格,因此在我尝试实际使用$args
数组内的call_user_func_array
函数之前,一切都是绝对正常的。是否有一些微妙的细节我忽略了调用该数组?我已经阅读了一遍PHP手册中关于call_user_func_array
函数的内容,然后再读了一些例子,这些例子似乎只是展示了人们如何构建一个数组并将其用作第二个参数。我可能做错了什么?
call_user_func_array
确实成功调用了构造函数,因为它给了我一个PHP警告:Product::__construct()缺少参数1
,对于特定构造函数期望的五个参数中的每一个,但由于某种原因没有接收到。当然,这可能是我还不理解的东西,但那是我目前所拥有的知识。 - tuespetrenew $class
实例化对象。这意味着在call_user_func_array
开始执行之前,构造函数已经被调用了。你明白吗?首先是new
,因为你将其作为参数中的表达式使用,然后才是函数调用。但由于new
已经被执行,所以$class
的构造函数已经被调用了(没有参数)。然后 PHP 尝试将对象转换为字符串,因为第一个参数需要一个字符串或数组。由于你的对象不支持转换为字符串,所以会出现错误/警告。 - hakre