【问题标题】:Why is mysql_fetch_object failing when class_name is null even though that's the default?为什么当 class_name 为 null 时 mysql_fetch_object 会失败,即使这是默认值?
【发布时间】:2011-07-26 03:28:10
【问题描述】:

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

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 ...

问题是我不希望它使用类名。我只是希望它执行默认行为,就好像我没有指定类名一样。

为什么会失败?

【问题讨论】:

    标签: php mysql object


    【解决方案1】:

    默认为空。默认值为stdClass(来自文档):

    要实例化、设置属性和返回的类的名称。如果未指定,则返回 stdClass 对象。

    如果您想保持相同的默认值,您需要将此作为您的方法签名:

     public function get_objects($sql, $class_name = "stdClass") {
         // continue as normal.
    

    【讨论】:

    • 我认为应该引用类名。
    • 如果他发送一个虚假的第二个参数会发生什么?
    • 如果他发送mysql_fetch_object($result, "invalid string")会发生什么?它失败并输出错误。
    【解决方案2】:

    如果你不想指定一个特定的类,那你为什么还要使用 class_name 参数呢?

    如果你绝对必须使用它,这应该可以工作

    if ( $result ) {
       $class_name = $class_name ? $class_name : 'stdClass';
       ...
    

    【讨论】:

    • 因为他想要“passthru”形成他的自定义函数,所以他需要有一个默认...
    【解决方案3】:

    也许是因为它需要一个字符串,而你给它 null。我会做一个 if 检查以查看 $class_name!=null 是否。

    public function get_objects($sql, $class_name = null) {
        $result = mysql_query( $sql, $this->connection );
        $objs = array();
        if( $result ) {
            if ($class_name){
                while ($obj = mysql_fetch_object($result, $class_name)) {
                    $objs[] = $obj;
                }
            }else{
                while ($obj = mysql_fetch_object($result)) {
                    $objs[] = $obj;
                }
            }
            mysql_free_result($result);
        }
        return $objs;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多