Get and set properties in PHP (dynamically)
I worked in PHP 5.3 and I created some interesting stuff. But the most interesting thing about the classes are the properties of a class…
There is no big changes since PHP 4 except the visibility. Now variables can be public, protected or public. This is not a big behavior as every object-oriented language has defined this. Basically, you simply declare your properties like this:
class MyObject {
public $myProperty;
}
If you look carefully in the PHP documentation, you will find you can access your property simply writing $myInstance->myProperty where $myInstance is an instance of the object (as for any other language).
Which is interesting is the capability of PHP (same for Ruby, I do agree) to be fully dynamic. Then you can retrieve all the properties available (and their values) through the get_object_vars($myInsance) call. Then you get all your properties in an array (which is a hash table or a Map for Java developers).
This is good, then you know how to get the properties dynamically: if you have the name of the property stored in a variable, you get its value as show above. What about setting the value of a property?
Well, I try to find the answer in Google but I failed. No way to set dynamically a property (except using the __set() method but this one do not work on declared properties!). I looked for a set_object_vars() method, but nothing!
In fact, it is VERY simple: $myInstance->$propertyName is the solution. Simply note the “$” sign after the “->”: it means $propertyName is not the property name but a variable having the property name stored inside. That’s all. Very simple but no way to find it in a blog or in PHP documentation.
To be clear: $myInstance->$propertyName is equivalent to $myInstance->myProperty when $propertyName = "myProperty". See the code below (I changed names), at the end, the code will display “It works!”:
<?php
class TestIt {
public $hook;
}
$o = new TestIt();
$varname = "hook";
$o->hook = "Initial value";
$o->$varname = "It works!";
echo $o->hook;
?>
Impressive (and amazing), isn’t it?
Then I should be able to create a fully dynamic library to manipulate data between the database, the entity as an mapped object/relational and a simple form to input the data. If I have to write something in PHP, I will publish the code.
-
Archives
- October 2011 (1)
- September 2011 (7)
- April 2011 (1)
- February 2011 (1)
- January 2011 (1)
- December 2010 (1)
- October 2010 (1)
- August 2010 (3)
- July 2010 (1)
- February 2010 (2)
- January 2010 (3)
- July 2009 (1)
-
Categories
-
RSS
Entries RSS
Comments RSS
