unemployment Posted July 6, 2011 Share Posted July 6, 2011 I found this tide bit of code in my lib files. Why use a __contruct() // Sets the username and password if given. public function __construct($user = null, $pass = null){ parent::__construct(); if ($user !== null && $pass !== null){ $this->youtube_user = $user; $this->youtube_pass = $pass; } } Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/ Share on other sites More sharing options...
xyph Posted July 6, 2011 Share Posted July 6, 2011 Why not? Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/#findComment-1239112 Share on other sites More sharing options...
PFMaBiSmAd Posted July 6, 2011 Share Posted July 6, 2011 From the php.net OOP documentation - Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/#findComment-1239114 Share on other sites More sharing options...
unemployment Posted July 6, 2011 Author Share Posted July 6, 2011 From the php.net OOP documentation - Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. So my understanding of this is... that it is used to initialize the rest of the class? With reference to this example, if you don't have the user name and password, then you can't use the rest of the class, right? Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/#findComment-1239117 Share on other sites More sharing options...
xyph Posted July 7, 2011 Share Posted July 7, 2011 No, $user and $pass have default values, so they don't HAVE to be called. Whether other methods in that class need those values, I have no idea. Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/#findComment-1239670 Share on other sites More sharing options...
AyKay47 Posted July 7, 2011 Share Posted July 7, 2011 as PFMaBiSmAd stated, using __construct allows you to do any sort of initializing of properties etc. without actually have to call a function. It is triggered by the creation of a new object In your case, its sets the properties $user and $pass for use inside of the class Link to comment https://forums.phpfreaks.com/topic/241228-why-use-__construct/#findComment-1239707 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.