note 95489 added to language.types.object
| From: | Anonymous at osu1 dot php dot net | Date: | Tue, 05 Jan 2010 22:10:20 +0000 |
| Subject: | note 95489 added to language.types.object | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-164672@lists.php.net to get a copy of this message | ||
Initialization, Instantiation and Instances are terms that can be confusing at first. Let's try
to sort it out starting with this simple class definition.
<?php
class User
{
public $first_name;
public $last_name;
public function __toString()
{
return "User [first='$this->first_name',
last='$this->last_name']";
}
}
?>
Now create several INSTANCES of User by INSTANTIATING the User class above.
<?php
$user_1 = new User; // $user_1 is an INSTANCE of User
$user_2 = new User; // $user_2 is an INSTANCE of User
echo $user_1 . '<br>'; // User [first='', last='']
echo $user_2 . '<br>'; // User [first='', last='']
?>
Here we have (2) two INSTANCES of User, but each instance was only INSTANTIATED once - when we used
the 'new' operator.
And now looking at the printed output, you can see there are no values for their first or last
names. This means that the objects themselves have NOT been INITIALIZED. To remedy this situation,
rewrite the class definition by adding a __construct() method.
<?php
class User
{
public $first_name;
public $last_name;
public function __construct($first, $last) // Require first and last names when INSTANTIATING
{
$this->first_name = $first; // INITIALIZE $first_name;
$this->last_name = $last; // INITIALIZE $last_name;
}
public function __toString()
{
return "User [first='$this->first_name',
last='$this->last_name']";
}
}
?>
Now try it again.
<?php
$user_1 = new User('John', 'Doe'); // $user_i is an INSTANCE of User
$user_2 = new User('Jane', 'Doe'); // $user_2 is an INSTANCE of User
echo $user_1 . '<br>'; // prints: User [first='John',
last='Doe']
echo $user_2 . '<br>'; // prints: User [first='Jane',
last='Doe']
?>
The __construct() method is called automatically by PHP when it sees the 'new' operator.
Our __construct() method above requires the first and last names to be passed in as arguments and
uses them to INITIALIZE objects when INSTANTIATING new INSTANCES.
----
Server IP: 69.147.83.197
Probable Submitter: 69.19.176.172
----
Manual Page -- http://www.php.net/manual/en/language.types.object.php
Edit -- https://master.php.net/note/edit/95489
Del: integrated -- https://master.php.net/note/delete/95489/integrated
Del: useless -- https://master.php.net/note/delete/95489/useless
Del: bad code -- https://master.php.net/note/delete/95489/bad+code
Del: spam -- https://master.php.net/note/delete/95489/spam
Del: non-english -- https://master.php.net/note/delete/95489/non-english
Del: in docs -- https://master.php.net/note/delete/95489/in+docs
Del: other reasons-- https://master.php.net/note/delete/95489
Reject -- https://master.php.net/note/reject/95489
Search -- https://master.php.net/manage/user-notes.php