why use __construct()?
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?
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:
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);
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread