Apr 04 2008
Some PHP Abilities You May Not Know About
Throughout my time programming PHP I've come across a few interesting things about the language. Coming from a primarily Java background, it seems quite strange to be able to do some of these things so easily.
Having said that, here are a few things with PHP that I've found interesting, and hopefully some of these things you've never heard about.
Call a PHP function from a string
PHP is an interesting language. To do the following in Java, it would be much more complex - around 5-10 lines of code. In PHP however, it is quite simple to call a function dynamically from a string.
<?php $call_this = "phpinfo"; $call_this(); ?>
You can even pass arguments to the variable like you were calling the function directly - it's pretty cool. Here's a practical example: Consider a function that accepts either a jpeg or png image file and resizes it (this is only a subset of the function).
<?php switch($imgType){ case "jpeg": $create = "imagecreatefromjpeg"; break; case "png": $create = "imagecreatefrompng"; break; } $create($filename); //this will create either a jpeg or png ?>
This makes the code considerably cleaner by dynamically setting the function that will be called.
Ternary operator
This is a quick way to write an IF statement, without the structure and braces. The way it works is like a normal if statement, you pass it true or false (in the following case, ($test == true) == true), and then the ? means then and the : means else. It's pretty simple, and is nice to use for simple one liners, in cases like the following example.
<?php $test = true; echo $test == true ? "is true!" : "not true"; //will print "is true!"; ?>
A little bit nicer than
<?php $test = true; if($test == true){ echo "is true!"; }else{ echo "not true"; } ?>
Easily echo a variable
I don't really like this method, I prefer to just use <?php echo "string"; ?>, but maybe this way is faster - I'm not sure. Either way, pretty much all it does is echo the variable that is after the equals sign.
<?php $val = 50; ?> <!-- some HTML or whatever --> <?= $val ?>
Variable variables
Variable variables are variables that can be dynamically set with strings. In the following code, you will notice that we set the variable $val to "hello" and then set the variable variable (the string that $val holds ("hello")) to the string "variable variable". When we echo $hello, the text "variable variable" will be printed.
<?php $val = 'hello'; $$val = 'variable variable'; //the string that is set in $val is now the name of our variable. echo $hello; //will print 'variable variable' ?>
Calling a variable variable function
Expanding on the variable variables, you could actually combine that example with calling a PHP function by a string and do this:
<?php $val = 'show_info'; $$val = 'phpinfo'; echo $show_info(); //will echo phpinfo() ?>
Here, "show_info" is the name of the variable, and its pointing to "phpinfo" Writing $show_info() calls the function that the variable variable is pointing to. It's kind of confusing and would probably only be used in some really complex code, but it does work.
Like this post? Subscribe to the full RSS feed.
Comments RSS feed | Trackback URI
38 Comments »
Trackback responses to this post
- David Jeffries » Tips For StumbleUpon Traffic To Your Blog
- Some Things In PHP You May Not Know About at Return True
- Webmasterdays BackOffice » Blog Archive » Must read - Some PHP Abilities You May Not Know About
- Best Of April 2008 | Best of the Month | Smashing Magazine
- Best Of April 2008 - Glimpses of the Aleph
- phpblog.it
- David Jeffries » Some More PHP Abilities You May Not Know About
- PHP: Funktionen dynamisch aufrufen « lab111

Avoid <?= $var ?> as it won’t work when short open tags is disabled - something that is becoming the norm on some hosts. Short open tags break xhtml. Best to stick with <?php echo $var; ?> if you’re writing deployable code.
The “Quick If statement” is called a ternary operator.
Thanks Joey, I never knew it was called that
You can still do and it will work with short open tags disabled. It’s three extra characters, but you don’t have to use echo and the semicolon is not required.
Variable variables… I’ve been looking for a way to do that for ages! The months I’ve been limiting my applications for want of being able to do this. Thanks a lot
Really cool post. Didn’t know about the $$ thingy
Pretty cool.
adam, This argument is one of the most frustrating things about the php community. Which is easier to type; or
As for validating xhtml, I don’t care if the source code validates, what matters is if the output validates. I fail to understand why the php community is so adament about the validation thing - source code doesn’t need to validate against sgml, it needs to validate against the php parser. The output needs to validate against the proper sgml spec.
php -> php parser. xhtml -> xhtml DTD. what’s so hard about that?
Oh nice, the blog cut my code.
Try this:
adam, This argument is one of the most frustrating things about the php community. Which is easier to type; <?php= $foo ?> or <php echo $foo ?>
As for validating xhtml, I don’t care if the source code validates, what matters is if the output validates. I fail to understand why the php community is so adament about the validation thing - source code doesn’t need to validate against sgml, it needs to validate against the php parser. The output needs to validate against the proper sgml spec.
php -> php parser. xhtml -> xhtml DTD. what’s so hard about that?
DGM - the problem isn’t you source code validating (And I am not in any way saying the source code needs to validate!) but rather if you have short open tags enabled - php will parse the opening xml tag as php - breaking your xml document. This is about the php parser - and has nothing to do with the xhtml parser and validation.
For Example:
<?xml version=”1.0″ encoding=”ISO-8859-15″?>
is an xml opening tag. If you have short open tags enabled on your host - the php parser will eval this and either throw an error - or ignore the line without outputting it to the browser resulting in a malformed XML response delivered to the client.
There is a way to get around this - by manually echoing out the entire string *however* this is messy and demonstrates why short open tags shouldn’t be used - and why a lot of larger (i.e the ones I deal with corporate level) hosts don’t have it enabled.
So from your point of view as a developer - the reason for not using short open tags is to ensure your application will work without problems on the widest range of hosts. This is especially important for code/application you are distributing in which case you are unlikely to be the one trying to get your application up and running in the first place.
I am definitely not a standards Nazi and my blog details many arguments to the contrary; but this isn’t about standards its about maximising the “success” of your own code.
“I am definitely not a standards Nazi and my blog details many arguments to the contrary; but this isn’t about standards its about maximising the “success” of your own code.”
Nice comment..
I would never hire you.
It is about web standards guy.
Twit… “This isn’t about standards” was refering to the point about not using <? instead of <?php - not the arguement for or against standards. My referece to standards was not saying they were bad (far from) but to explain to DGM that I wasn’t just telling him not to use it because it breaks standards; but that it will also break the deployablity of his code.
I think most languages have the ternary operator. Java does! And so does C!
Neat list. I was aware of some of these, but it’s nice to have them referenced together.
There’s no ternary operator in Java?
There is a ternary operator in Java, and like Octopus said C has it as well. Javascript, ruby, asp, and most other popular languages support it.
I was mainly talking about dynamic functions and variable variables being difficult in Java versus being quite simple in PHP. The ternary operator is just something that many people haven’t heard of, or don’t know how it works - so I included it in this list.
Dynamic variables don’t exist in Java because its a strongly typed statically linked language. This is why PHP is much better suited to web scripting than Java/JSP.
You could use Generics in Java to do something similar to your “variables variables”.
Thanks for the article, I didn’t know about calling functions from strings.
argh!
This is bad:
It should be
Some interesting PHP tips, thanks for sharing.
I enjoyed your post, and learned something as well. The ternary operator tip is going got make my code much cleaner.
Thanks!!
This is great. This is just what i needed to finish my php project.
Thanks
Good tips for the beginners.
About variable variables, you can also use concatenation :
$test = ‘blah’;
${$test.’2′} = ‘bloh’;
echo $blah2 // outputs ‘bloh’
Calling functions from variable might seem to be a neat feature, but I’d suggest using
call_user_func();for the sake of readability. In long blocks of code it’s hard to spot the extra
$in front of function name, and it might even be harder to understand what it means in a given context.Why people use comparison with boolean constants?
$test == truedoes the same as just$testwhile$test == falseis equivalent to!$test.Jonas: That also baffles me. I guess it takes into account data types etc as well.
You caught me on a couple there!
Pretty cool!!!!!!!!!!!!!!!
IMO the ternary operator shouldn’t be used. It makes the code harder to read and really doesn’t help efficency. I don’t see a point in it.
if($var){
//do something
} else {
//do something else
}
That looks way cleaner.
Consider this example, when adding a class of selected to an element.
$class = $selected == true ? ‘ selected’ : ”;
echo ‘<div class=”‘.$class.’”> </div>’;
versus:
if($selected){
$class = ‘ selected’;
}else{
$class = ”;
}
echo ‘<div class=”‘.$class.’”> </div>’;
Many people will prefer the ternary operator and argue that it is cleaner than the long way (in some situations).
I agree. In that case I would probably use the ternary op. just to save time and space. The problem is that A LOT of people don’t know how to use the ternary operator and don’t understand what it means when they see it.
If you’re working at a big company its easier to use the long way because every person understands that logic whereas most people won’t understand the short way. I know how to use the ternary operator and I can still figure out what I’m trying to do quicker if I do the long way.