2

I'm wondering why in the PHP code below, the PDO objects $db is passed as NULL. i.e. $db=NULL in the constructor parameter.

class ColoredListsUsers
{
    /**
     * The database object
     * @var object
     */
    private $_db;

    /**
     * Checks for a database object and creates one if none is found
     * @param object $db
     * @return void
     */
    public function __construct($db=NULL) /* why is #db passed as null here ? */
    {
        if(is_object($db))
        {
            $this->_db = $db;
        }
        else
        {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
            $this->_db = new PDO($dsn, DB_USER, DB_PASS);
        }
    }
}

Earlier $db was declared as a PDO object:

// Create a database object
    try {
        $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
        $db = new PDO($dsn, DB_USER, DB_PASS);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit;
    }

Just doesn't seem to make sense to make $db a PDO object then pass it as null.... code is from http://www.copterlabs.com/blog/creating-an-app-from-scratch-part-5/

4

1 回答 1

3

public function __construct($db=NULL)手段$db 是一个可选参数。如果未指定,则将使用默认NULL值。

在这种情况下 - 看看下面的几行,else主体 - 创建默认连接。

于 2013-05-16T02:32:24.040 回答