note 68650 deleted from language.oop5 by colder

From: Date: Sun, 19 Aug 2007 23:34:48 +0000
Subject: note 68650 deleted from language.oop5 by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-129625@lists.php.net to get a copy of this message
Note Submitter: markfarquaad at gmail dot com ---- 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

« previous php.notes (#129625) next »