Jump to content

Why use __construct();


unemployment

Recommended Posts

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.