Jump to content

Help in Step 13 of OOP - PHP Tutorial


sectorclear01

Recommended Posts

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! :)

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...