Skip to content

Get and set properties in PHP (dynamically)

September 23, 2011

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

  class TestIt {
  	public $hook;

  $o = new TestIt();
  $varname = "hook";
  $o-&gt;hook = "Initial value";
  $o-&gt;$varname = "It works!";

  echo $o-&gt;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.


From → Computers

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: