PHP Data Objects

I’m just beginning to learn about PHP Data Objects, and all seems to be going well so far.

However - I’m getting a bit confused over the syntax in the following example:


$STH->setFetchMode(PDO::FETCH_ASSOC);

Could somebody kindly explain, or provide resources that explain:
a) Why we are setting a fetch mode (and what the differences are) / why we need to do this; and
b) What is with the syntax PDO::FETCH_ASSOC ? I guess this is more of a general OOP question, but I (think) it’s to do with classes. When / why is it different to calling a property using -> to :: .

Many thanks

Setting the fetch mode on a PDOStatement object determines what format your results will be returned in when you call $stmt->fetch(). You can find a full list of the options here: www.php.net/manual/en/pdo.constants.php, but some of the more commonly used options are PDO::FETCH_ASSOC which returns the results as an associative array (i.e. with column names as array keys), PDO::FETCH_NUM which returns a numbered array, and PDO::FETCH_CLASS which will return each row as an instance of a class that you specify.

PDO::FETCH_ASSOC is a class constant. You call it directly on the class it belongs to, rather than an instance of the class, and they are defined with a class like this:


class PDO {
    const FETCH_ASSOC = 2;
}

Class constants are useful for passing options into a class method. If the value ever changes in future (from 2 to 7, for example), your code won’t break because you used the constant that represents the value you want.