sectorclear01 Posted October 12, 2012 Report Share Posted October 12, 2012 http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php Step 13: Constructors All objects can have a special built-in method called a 'constructor'. Constructors allow you to initialise your object's properties (translation: give your properties values,) when you instantiate (create) an object. Note: If you create a __construct() function (it is your choice,) PHP will automatically call the __construct() method/function when you create an object from your class. The 'construct' method starts with two underscores (__) and the word 'construct'. <?php class person { var $name; function __construct($persons_name) { $this->name = $persons_name; } function set_name($new_name) { $this->name = $new_name; } function get_name() { return $this->name; } } ?> My Note: Sir/Madam, I didn't get the use of method __construct, but no problem with other methods there. If possible, a sample of View Page that uses the __construct will be more clear. Thank you for your response! Quote Link to comment Share on other sites More sharing options...
falkencreative Posted October 12, 2012 Report Share Posted October 12, 2012 Take this example: <?php class person { var $name; function __construct($persons_name) { $this->name = $persons_name; } function set_name($new_name) { $this->name = $new_name; } function get_name() { return $this->name; } } ?> When the object is first created, with these lines: $object = new person('Ben'); the constructor ("__construct()") is called automatically. It will take the text that you provided ("Ben"), and set the $name property (referred to as $this->name, since it's part of the object) to the string that you specified. A constructor is most often used to set up the properties that the object needs to function. Hope that helps? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.