I have read the php manual as well as a stackoverflow question about the __construct() method. I still can not understand what it does and what is the reason for it. Can someone break it down for me?
@NogDogMay 13.2014 — #It is a method that automatically gets called any time you create a new instance of that class, so you define it if there is any processing that needs to happen upon creation of an object (i.e. use the "new" keyword). Similarly, there is a __destroy() method that gets called whenever that object is unset() or otherwise destroyed, though that tends to be much less used than __construct() (with most classes, programmers don't really care what happens when the object is no longer needed).
__construct() is often used to populate data required for an object, forcing the calling code to supply required parameters, rather than depending on it to specifically call one or more other methods to do so. For example, if my Foo class needs a PDO object to do its database operations, I can make it a required parameter of the __construct method: [code=php] class Foo { private $pdo;
public function __construct(PDO $pdo) { $this->pdo = $pdo; }
// other methods, some of which use $this->pdo... }
// this will work: $db = new PDO($dsn, $user, $pass); $good = new Foo($db);
// this will cause a fatal error: $bad = new Foo();
// this will also fail: $db = "not a PDO object"; $oops = new Foo($db); [/code]