php - 为什么 mysql_fetch_object 在 class_name 为 null 时失败,即使这是默认值?

标签 php mysql object

我正在尝试编写一个简单的数据库包装器类。我写了一个这样的方法:

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/

相关文章:

PHP 面向对象 : business logic layer - DB layer

Python未在MySQL服务器中注册

mysql - Mysql如何对三张多列表进行联合查询,只获取一个id

c# - 自动选择和创建类对象

C++:在对象指针中为字符串赋值时的第一次机会异常

php - 这段代码是否安全,不会受到任何 SQL 注入(inject)攻击?

用于重复事件的 PHP 5.3 DateTime

javascript - 仅通过 jQuery 请求显示 PHP 数组的新内容

php - 数据未插入MySQL数据库,但没有错误

ios - 如何检查 NSArray 中的空对象