Getting Smarter Code with PHP Variable Variables and Variable Functions

Posted in Coding, PHP, Tutorials3 years ago • Written by 29 Comments

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:

<?php
	$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 php.net 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:

<?php
	$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:

<?php
/*******************
OUR CLASS
********************/
	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;
		}
	}

/****************
WHEN SAVE OUR PRODUCT
*****************/
	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 )

/***************
WHEN SET OUR SHIPMENT PRICE
****************/
	$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 php.net manuals, about variable variablesvariable functions, and the magic get_class_methods php function.

43 Written ArticlesWebsiteGoogle+

I'm a web designer and entrepreneur from Itajubá (MG), Brasil. I love writing about obscure topics and doing some cool stuff. And also I do some FREE stuff, check it out: http://www.roch.com.br/

29 Comments Best Comments First
  • Daniel

    Friday, June 10th, 2011 15:42

    3

    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

    +1
    • Rochester Oliveira

      Friday, June 10th, 2011 17:37

      1

      Hey Daniel, you are right!

      Rean had changed it for us, thank you for pointing it out.

      []‘s

      0
  • Benjamin

    Monday, June 20th, 2011 18:32

    12

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

    0
    • Rochester Oliveira

      Monday, June 20th, 2011 19:27

      11

      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!

      []‘s

      0
      • Ben

        Tuesday, June 21st, 2011 05:37

        13

        Thank you, Rochester! :D

        So, I can do something like this, right?
        {$class_methods[$myMethod]}($data);
        ———->

        Anyway, I’ll make a try.
        Thanks♪♪

        0
        • b_wa

          Tuesday, June 21st, 2011 05:40

          14

          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.
          Thanks♪♪

          0
          • Rochester Oliveira

            Tuesday, June 21st, 2011 14:49

            15

            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!

            []‘s

            0
  • Josh Bedo

    Monday, June 13th, 2011 08:43

    9

    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.

    0
    • Rochester Oliveira

      Monday, June 13th, 2011 16:50

      10

      Hey Josh, thank you!

      If you get in trouble, just come here again and ask for help :D

      []‘s

      0
  • Dave

    Saturday, June 11th, 2011 01:02

    5

    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.

    0
    • Rochester Oliveira

      Sunday, June 12th, 2011 06:04

      8

      Hey dave, this is what I was talking about! :D

      I really forgot to mention when all this thing don’t work, good point!

      Thank you!
      []‘s

      0
  • Adam

    Saturday, June 11th, 2011 01:07

    6

    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.

    0
    • Rochester Oliveira

      Sunday, June 12th, 2011 05:58

      7

      Really good point, Adam.

      It will be helpful to keep my code very clear. Thank you!

      []‘s

      0
  • Web dizajn

    Thursday, October 20th, 2011 12:02

    26

    This is useful,thanks

    0
    • Rochester Oliveira

      Tuesday, October 25th, 2011 13:34

      27

      I’m glad you liked! :)

      []‘s

      0
  • Mark

    Thursday, October 27th, 2011 13:41

    28

    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!

    0
    • Rochester Oliveira

      Friday, November 4th, 2011 14:49

      29

      Yeah, variable variables are kinda crazy indeed.

      Thanks :)

      []‘s

      0
  • Michael Francis

    Sunday, September 18th, 2011 04:21

    24

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

    0
    • Rochester Oliveira

      Monday, September 19th, 2011 16:44

      25

      Hi Michael,

      Sorry, I’ll try to explain myself a little better next time :)

      []‘s

      +1
  • shin

    Wednesday, June 29th, 2011 17:52

    16

    This reminds me another useful function call_user_func.

    0
    • Rochester Oliveira

      Thursday, June 30th, 2011 04:22

      17

      Hey shin, it is a good alternative to variable functions indeed.

      Thank you!

      []‘s

      0
  • Gogi

    Monday, September 12th, 2011 10:00

    21

    You a really a master of this branch.Thanks for this another great post on php.thanks

    0
    • Rochester Oliveira

      Monday, September 12th, 2011 18:15

      23

      Hey Gogi, thanks again!

      And we have much more to go, keep coming! :)

      []‘s

      0
  • thiet ke web dep

    Wednesday, September 7th, 2011 06:52

    20

    In part Variable Arrays , i used extract() function of PHP , result look like . Who can tell me know which case i can use this function. thanks alot

    0
    • Rochester Oliveira

      Monday, September 12th, 2011 18:14

      22

      Sorry man, wordpress seem to have stripped all of your tags.

      Can you send me an email or repost it without « and » ?

      []‘s

      0
  • peter

    Friday, June 10th, 2011 14:07

    2

    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”;

    Then:
    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…

    -1
    • Rochester Oliveira

      Friday, June 10th, 2011 17:46

      4

      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:
      [?php
      $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]

      ?]

      +1
      • ofir

        Friday, August 5th, 2011 11:57

        19

        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?

        +1
        • Rochester Oliveira

          Friday, August 5th, 2011 15:07

          18

          Hi ofir,

          Yeah, I’ve made a mistake here, I’ll ask to our editors to correct this, and thank you very much for pointing it out!

          []‘s

          0
  • Mark

    Thursday, October 27th, 2011 13:41

    28

    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!

    0
    • Rochester Oliveira

      Friday, November 4th, 2011 14:49

      29

      Yeah, variable variables are kinda crazy indeed.

      Thanks :)

      []‘s

      0
  • Web dizajn

    Thursday, October 20th, 2011 12:02

    26

    This is useful,thanks

    0
    • Rochester Oliveira

      Tuesday, October 25th, 2011 13:34

      27

      I’m glad you liked! :)

      []‘s

      0
  • Michael Francis

    Sunday, September 18th, 2011 04:21

    24

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

    0
    • Rochester Oliveira

      Monday, September 19th, 2011 16:44

      25

      Hi Michael,

      Sorry, I’ll try to explain myself a little better next time :)

      []‘s

      +1
  • Gogi

    Monday, September 12th, 2011 10:00

    21

    You a really a master of this branch.Thanks for this another great post on php.thanks

    0
    • Rochester Oliveira

      Monday, September 12th, 2011 18:15

      23

      Hey Gogi, thanks again!

      And we have much more to go, keep coming! :)

      []‘s

      0
  • thiet ke web dep

    Wednesday, September 7th, 2011 06:52

    20

    In part Variable Arrays , i used extract() function of PHP , result look like . Who can tell me know which case i can use this function. thanks alot

    0
    • Rochester Oliveira

      Monday, September 12th, 2011 18:14

      22

      Sorry man, wordpress seem to have stripped all of your tags.

      Can you send me an email or repost it without « and » ?

      []‘s

      0
  • shin

    Wednesday, June 29th, 2011 17:52

    16

    This reminds me another useful function call_user_func.

    0
    • Rochester Oliveira

      Thursday, June 30th, 2011 04:22

      17

      Hey shin, it is a good alternative to variable functions indeed.

      Thank you!

      []‘s

      0
  • Benjamin

    Monday, June 20th, 2011 18:32

    12

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

    0
    • Rochester Oliveira

      Monday, June 20th, 2011 19:27

      11

      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!

      []‘s

      0
      • Ben

        Tuesday, June 21st, 2011 05:37

        13

        Thank you, Rochester! :D

        So, I can do something like this, right?
        {$class_methods[$myMethod]}($data);
        ———->

        Anyway, I’ll make a try.
        Thanks♪♪

        0
        • b_wa

          Tuesday, June 21st, 2011 05:40

          14

          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.
          Thanks♪♪

          0
          • Rochester Oliveira

            Tuesday, June 21st, 2011 14:49

            15

            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!

            []‘s

            0
  • Josh Bedo

    Monday, June 13th, 2011 08:43

    9

    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.

    0
    • Rochester Oliveira

      Monday, June 13th, 2011 16:50

      10

      Hey Josh, thank you!

      If you get in trouble, just come here again and ask for help :D

      []‘s

      0
  • Adam

    Saturday, June 11th, 2011 01:07

    6

    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.

    0
    • Rochester Oliveira

      Sunday, June 12th, 2011 05:58

      7

      Really good point, Adam.

      It will be helpful to keep my code very clear. Thank you!

      []‘s

      0
  • Dave

    Saturday, June 11th, 2011 01:02

    5

    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.

    0
    • Rochester Oliveira

      Sunday, June 12th, 2011 06:04

      8

      Hey dave, this is what I was talking about! :D

      I really forgot to mention when all this thing don’t work, good point!

      Thank you!
      []‘s

      0
  • Daniel

    Friday, June 10th, 2011 15:42

    3

    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

    +1
    • Rochester Oliveira

      Friday, June 10th, 2011 17:37

      1

      Hey Daniel, you are right!

      Rean had changed it for us, thank you for pointing it out.

      []‘s

      0
  • peter

    Friday, June 10th, 2011 14:07

    2

    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”;

    Then:
    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…

    -1
    • Rochester Oliveira

      Friday, June 10th, 2011 17:46

      4

      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:
      [?php
      $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]

      ?]

      +1
      • ofir

        Friday, August 5th, 2011 11:57

        19

        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?

        +1
        • Rochester Oliveira

          Friday, August 5th, 2011 15:07

          18

          Hi ofir,

          Yeah, I’ve made a mistake here, I’ll ask to our editors to correct this, and thank you very much for pointing it out!

          []‘s

          0

Comments are closed.

54.225.18.187 - unknown - unknown - US