我正在尝试编写一个简单的数据库包装器类。我写了一个这样的方法:
public function get_objects($sql, $class_name = null) {
$result = mysql_query( $sql, $this->connection );
$objs = array();
if( $result ) {
while ($obj = mysql_fetch_object($result, $class_name)) {
$objs[] = $obj;
}
mysql_free_result($result);
}
return $objs;
}
如果我在调用此方法时未指定 $class_name,则对 mysql_fetch_object 的调用将失败并出现以下错误:
PHP Fatal error: Class '' not found in ...
问题是我不希望它使用类名。我只是希望它执行默认行为,就好像我没有指定类名一样。
为什么会失败?
最佳答案
默认不是 null。默认值为 stdClass (来自文档):
The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
如果你想保持相同的默认值,你需要将其作为你的方法签名:
public function get_objects($sql, $class_name = "stdClass") {
// continue as normal.
关于php - 为什么 mysql_fetch_object 在 class_name 为 null 时失败,即使这是默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6824920/