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!

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:

	$she = "loves";
	$loves = "you";
	$you = "she";

	echo $$loves." ".$$you." ".$$she; // ♫♫ yeah, yeah, yeah ♫♫
	// same that:
	// echo $you.$she.$loves;

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):

$a = "a";
for ($i = 1; $i <= 5; $i++) {
  ${$a.$i} = "value";

echo "$a1, $a2, $a3, $a4, $a5";
//Output is value, value, value, value, value

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:

	$i = 3; //we want the 4th item in the array

	$product = array ( 'TLP2844', 'OSX214Plus', 'E-4205', 'TTP244Plus' );
	$manufacturer = array ( 'Zebra', 'Argox', 'Datamax', 'TSC' );

	$select = $_GET['filter'];
        //hard way
        if ( $select == "product") {
        echo $product[$i];
         } else {
        echo $manufacturer[$i];

        //easy way
        echo ${$select}[$i];

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:

	class Shipping {
		function free( $data ) {
			return 0;

		function smallProduct( $data ) {
			$price = 100;
			return $price;

		function mediumProduct( $data ) {
			$price = 300;
			return $price;

		function fragileProduct( $data ) {
			$price = 1000;
			return $price;

	include ('pathToOurClassFile.php');
	$class_methods = get_class_methods('Shipping'); // Shipping is our class name!
	//$class_methods output Array ( [0] => free [1] => smallProduct [2] => mediumProduct [3] => fragileProduct )

	$myMethod = "mediumProduct"; //it should come from our BD, stored in product data

	$shipment = new Shipping();
	$price = $shipment-> $myMethod ( $data );
	echo $price;


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.



  1. Mark

    Some nice examples, the one regarding the switch replacement is especially useful for keeping your code a bit neater and understandable, something which doesn’t usually happen when using variable variables!

  2. Michael Francis

    Good idea… It could have been explained a little better for the beginners, but I understand the concept.

  3. Benjamin

    I can’t catch why you call the get_class_methods function.
    For what would you use $class_methods?

    • Hey b_wa,

      If you have a software where the user selects the behavior of one component, then it would be useful.

      For example, I’ve developed a software where the admin user can create shipment methods, and set which will be its behavior ( fixed rate, free, SEDEX, PAC.. ) via get_class_methods in myshipments class. So when we have a real costumer, the system gets the shipment prices based on DB record of which class method it should use.

      Hope it helps you too!


      • Ben

        Thank you, Rochester! :D

        So, I can do something like this, right?

        Anyway, I’ll make a try.

        • b_wa

          Thank you, Rochester! :D

          So, I can do something like this, right?
          $myMethod = “2”; // defined key for “mediumProduct”
          $price = $Shipping->{$class_methods[$myMethod]}($data);

          Anyway, I’ll make a try.

          • Oh yeah, it worked like a charm for me..

            Specially the $data parameters passed as array so I don’t need to go testing if this method has that parameter, I just get it inside the method itself :D

            If it doesn’t work, just come back and I’ll help you!


  4. Josh Bedo

    Very awesome tutorial thanks for the post i enjoyed reading it. Will have to mess around with this in some of my next projects this is a cool topic to learn more about.

  5. Adam

    This is a good intro to this topic, thanks. I prefer to use the curly braces all the time for this, to make it much more obvious that I’m using variable-variables. ${$something} is much more clear that I’m using a variable variable than just $$something to me.
    Another intesting thing to note is you can do this with class names. If you had a class called Person, and a variable $class = ‘Person’, you can just call $object = new $class(), and it will create a new Person, so you can do some interesting dynamic things this way.

  6. PHP supports the concept of the variable function. This means if you add the parentheses to the variable name then PHP will look for the function with the same name as that variable contain and will tried to execite that function. This is most useful to create a callback, function tables, etc..

    Variable functions won’t work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like.

  7. Daniel

    Thank you very much for this post, It is really useful , On the Variable Arrays to avoid confusions just add $select = $_GET[‘filter’]; in the easy way or keep out of the hard way n.n

  8. peter

    Sorry but I just found it confusing.. its supposed to be educational, so why call:
    $jude = “hey” and $hey = “jude”

    is it not less confusing to call:
    $jude = “jude” and $hey = “hey”.

    It got even more confusing with:
    $she = “loves”;
    $loves = “you”;
    $you = “she”;

    Quote:”If you echo $$jude $$hey(yeah, double “$”)”
    WHY DOUBLE $$, this is a tutorial, if I knew why to put double ‘$$’ I wouldn’t need to read it…

    • Hi Peter,

      The best way to learn this is really try the code. It IS confusing, really, but it can be really useful if you know what are you doing.

      Read with attention the article, it is all about variable variables, so you use one variable ($jude = hey) to call other variable ($hey). There is no reason to use $jude = jude since it will call itself. So you MUST TO understand what is going on when you call a variable with other.

      Let make another example:
      $first = ‘You put $hi as “first” ‘;
      $second = ‘You put $hi as “second” ‘;

      $hi = “first”; //change this to second and see what happens

      echo $$hi; //here we echo the var $[put here the value of hi you want]


      • ofir

        But won’t the output be “jude hey”?
        If $jude=”hey” and $hey=”jude”, than $$jude $$hey would translate to $hey $jude and the output would be jude hey…
        Am I missing something? I figured out the other example (she loves you) but not this one.
        What am I doing (thinking) wrong?