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 php.net documentation, you can do this (modified a little bit):
$a = "a";
for ($i = 1; $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' );
//hard way
$select = $_GET['filter'];
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:
/*******************
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 variables, variable functions, and the magic get_class_methods php function.
- Login om te reageren