/    Sign up×
Community /Pin to ProfileBookmark

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?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@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]
×

Success!

Help @ytesfay80 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...