Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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/

share|improve this question
You're not creating any ColoredListsUsers instances in the provided code. – zerkms 10 hours ago
It isn't being passed as NULL - that is a default parameter value for the constructor function. It allows one to omit the $db parameter, in which case it will be default NULL. – Michael Berkowski 10 hours ago

1 Answer

up vote 3 down vote accepted

public function __construct($db=NULL) means $db is an optional parameter. And if it's not specified then the default NULL value will be used.

In this case - look several lines below, the else body - the default connection is created.

share|improve this answer
Oh, so $db is always passed into the function; just if it has a value, the PDO, it retains it and the if() executes since it evaluates as an object, but if $db is passed without a value then it takes on the value of NULL and the else() executes? Am I thinking about this right? – Gnuey 9 hours ago
@Gnuey: "but if $db is passed without a value" --- this is incorrect. The correct would be: "but if nothing is passed". Like new ColoredListsUsers(); – zerkms 8 hours ago
Ah, ok. That's another explanation I was considering. Makes sense. Thank you. – Gnuey 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.