note 68650 added to language.oop5
| From: | markfarquaad at gmail dot com | Date: | Fri, 04 Aug 2006 21:23:57 +0000 |
| Subject: | note 68650 added to language.oop5 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-115560@lists.php.net to get a copy of this message | ||
Variable Object Attributes instead of variable variables:
Actually I figured this out on PHP 4.3, but I'm sure it works on the current PHP 5+:
If you like using variable variables and would like to use the same functionality with attributes of
class objects, here's how you can can get a specific attribute of a specific class with
variable OBJECTS:
Let's say this is our class:
class Car
{
var $brand;
var $color;
var $year;
function Car()
{
etc...
}
}
Let's say we have an object of Class 'Car', my own car, where $brand =
'Ferrari', $color='red', etc.:
$mycar = new Car();
And another 'Car' object, your car, where $brand='Porsche',
$color='black', etc.:
$yourcar = new Car();
Now we need a uniform code snippet to access the color attribute of anyone's 'Car',
but we would like to change the object dynamically outside the code delivering the color attribute.
Here's how:
The variable or dynamic part is the object (the car owner):
$objectName = 'mycar';
or
$objectName = 'yourcar';
etc...
The static reusable code to deliver the color of any object dynamically is:
$objectAttributeName = 'color';
$objectAttribute = ${$objectName}->$objectAttributeName;
Now:
echo $mycar->color;
will deliver exactly the same as:
echo $objectAttribute
THe difference is, with the dynamic version, you do not have to know $objectName in the static code
part, while in the non-variable version you must always specify the object name $mycar, $yourcar,
etc to access the obeject's attributes.
I hope this helps anyone who likes reusing code like I do.
Mark
----
Server IP: 66.163.161.117
Probable Submitter: 80.238.229.17
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/language.oop5.php
Edit -- https://master.php.net/note/edit/68650
Del: integrated -- https://master.php.net/note/delete/68650/integrated
Del: useless -- https://master.php.net/note/delete/68650/useless
Del: bad code -- https://master.php.net/note/delete/68650/bad+code
Del: spam -- https://master.php.net/note/delete/68650/spam
Del: non-english -- https://master.php.net/note/delete/68650/non-english
Del: in docs -- https://master.php.net/note/delete/68650/in+docs
Del: other reasons-- https://master.php.net/note/delete/68650
Reject -- https://master.php.net/note/reject/68650
Search -- https://master.php.net/manage/user-notes.php