Getting Smarter Code with PHP Variable Variables and Variable Functions

Oh, variables. Who doesn’t love them? They are such nice guys, you know. When you need something, just call $something and your value is there.

But something really cool is that you actually don’t need the name of the variable. You can use other variables to access a value of one variable.

For example, let’s say you have two variables $jude = "hey" and $hey = "jude". If you echo $$jude $$hey(yeah, double “$”) your output will be “hey jude”.

But, as you might be thinking it is not just about variables. You can name dynamic functions, methods, arrays, and almost anything you want to.

This time we will see some uses for it, with arrays, functions, classes and how this technique can help you write better code.

So, let’s rock!


preview large smarter tutorials css php css css

Why You Should Use It

Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

With variable variables and variable functions you can solve problems that would be much harder to solve without them. We will see some examples below, so I won’t spend long on this, I just want you to keep in mind that you have an option, dear padawan. You can do what your customer wants in a simple way.

Why You Shouldn’t Use It

As anything in our lives this too has a downside.

Truth be told, I don’t use variable variables all the time, and this is because they can make your code a mess. Believe me, for real, a mess.

Instead of reading $imTheProductID you have to read $$product and remember that it refers to product ID. Thus, use it with caution, and when you use it comment the code. I don’t want anybody saying “Oh, man, I’ll kill that Rochester. This guy made my code impossible to read!”

Let’s see what you can do with it.

Variable Ordinary Variables

This is the basic of the basic usage. As I said in my introduction, you can write:

1 <?php
2     $she = "loves";
3     $loves = "you";
4     $you = "she";
6     echo $$loves." ".$$you." ".$$she; // ♫♫ yeah, yeah, yeah ♫♫
7     // same that:
8     // echo $you.$she.$loves;
9 ?>

If you try this, you will see the output “She loves you”. As you may notice, this is quite confusing, so when you use it be careful.

But you can do much more than echo a song in unreadable variables. Let’s say you want to generate some dummy vars, for testing purposes, as Andre exemplified in documentation, you can do this (modified a little bit):

1 <?
2 $a = "a";
3 for ($i = 1; $i <= 5; $i++) {
4   ${$a.$i} = "value";
5 }
7 echo "$a1, $a2, $a3, $a4, $a5";
8 //Output is value, value, value, value, value
9 ?>

The important thing to note here is the curly brackets. They are, in this context, similar to parenthesis in math operations, they say to the PHP processor “Hey, you should first join $a to $i and then you create the variable”. With it you can create variables joining other values, and mixing with strings, with you want (if you do that, I would recommend you use single quotes to prevent PHP warnings).

Variable Arrays

Let’s say you have two groups of data, stored in arrays. If you want to switch between them, the usual way is create an if / else statement, right?

Well, you could do it via variable arrays. Lets see how it could be:

1 <?php
2     $i = 3; //we want the 4th item in the array
4     $product = array ( 'TLP2844', 'OSX214Plus', 'E-4205', 'TTP244Plus' );
5     $manufacturer = array ( 'Zebra', 'Argox', 'Datamax', 'TSC' );
7     $select = $_GET['filter'];
8         //hard way
9         if ( $select == "product") {
10         echo $product[$i];
11          } else {
12         echo $manufacturer[$i];
13         }
15         //easy way
16         echo ${$select}[$i];
17 ?>

Again, look at the curly brackets. If you don’t use them you will get an ugly error.

This is a very simple example, but you could apply this to many other things, and the main advantage is that if you add, let’s say, another 100 arrays, you don’t have to create 99 “if / elseif / else” statements (or switch, for the smarter programmers :D).

Variable Functions and get_class_methods

As the code above, variable functions is a good alternative to endless if / else or switches.

But another really good use of variable functions is dynamically define which method should be called, based on a variable. Well, examples are always better for this.

Let’s say you sell gadgets online. As a good seller, you have a lot of  transport companies that you use, but which one you will use depends on the product bought. When one of your 1,000 employees registers a new product it is saved which company it can use.

Again, if you use common logic you would use a switch, and when you add a new method, it would be a nightmare.

Here, what we could do is use our variable functions and when you save the product data, you also save its shipping method. The magic here is to use the get_class_methods to save the name of the method so we can save it and set it as our method name when we calculate the shipment price.

So it would be something like this:

1 <?php
2 /*******************
4 ********************/
5     class Shipping {
6         function free( $data ) {
7             return 0;
8         }
10         function smallProduct( $data ) {
11             $price = 100;
12             return $price;
13         }
15         function mediumProduct( $data ) {
16             $price = 300;
17             return $price;
18         }
20         function fragileProduct( $data ) {
21             $price = 1000;
22             return $price;
23         }
24     }
26 /****************
28 *****************/
29     include ('pathToOurClassFile.php');
30     $class_methods = get_class_methods('Shipping'); // Shipping is our class name!
31     //$class_methods output Array ( [0] => free [1] => smallProduct [2] => mediumProduct [3] => fragileProduct )
33 /***************
35 ****************/
36     $myMethod = "mediumProduct"; //it should come from our BD, stored in product data
38     $shipment = new Shipping();
39     $price = $shipment-> $myMethod ( $data );
40     echo $price;
42 ?>

Are you hungry yet?

I think it is a really interesting topic. Why not read a little bit more about it? My main source was manuals, about variable variablesvariable functions, and the magic get_class_methods php function.

By Rz Rasel Posted in Php

4 comments on “Getting Smarter Code with PHP Variable Variables and Variable Functions

  1. Hey There. I found your weblog using msn. This is a really neatly written article. I will be sure to bookmark it and return to read extra of your helpful info. Thanks for the post. I’ll definitely comeback.

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