Apr 04 2008

Some PHP Abilities You May Not Know About

by David Jeffries under Programming at 7:24 pm


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 »

Comment by adam
2008-04-05 23:08:27

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.

 
Comment by Joey
2008-04-06 05:29:57

The “Quick If statement” is called a ternary operator.

 
Comment by David Jeffries
2008-04-06 10:26:16

Thanks Joey, I never knew it was called that

 
Comment by Garr
2008-04-06 12:14:20

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.

 
Comment by Audigex
2008-04-06 16:17:42

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

 
Comment by Sava
2008-04-06 16:32:46

Really cool post. Didn’t know about the $$ thingy :D
Pretty cool.

 
Comment by DGM
2008-04-07 06:57:04

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?

 
Comment by DGM
2008-04-07 06:59:13

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?

Comment by Adam
2008-04-13 01:02:12

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.

Comment by Adamz
2008-05-21 09:14:04

“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.

(Comments wont nest below this level)
Comment by Adam
2008-06-16 19:42:00

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.

 
 
 
 
Comment by Octopus
2008-04-07 20:55:14

I think most languages have the ternary operator. Java does! And so does C!

 
Comment by Regan Johnson
2008-04-08 22:01:28

Neat list. I was aware of some of these, but it’s nice to have them referenced together.

 
Comment by Mark McDonagh
2008-04-10 13:12:38

There’s no ternary operator in Java?

Comment by David Jeffries
2008-04-10 13:22:53

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.

 
 
Comment by Pras Sarkar
2008-04-11 08:41:00

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

 
Comment by Lauxa
2008-04-18 08:30:35

Thanks for the article, I didn’t know about calling functions from strings.

 
Comment by Markus
2008-04-22 02:42:01

argh!

This is bad:

It should be

 
Comment by James Carlos
2008-04-22 18:07:07

Some interesting PHP tips, thanks for sharing.

 
Comment by Dustin Church
2008-04-24 11:17:00

I enjoyed your post, and learned something as well. The ternary operator tip is going got make my code much cleaner.

Thanks!!

 
Comment by Learn to code
2008-04-28 15:04:28

This is great. This is just what i needed to finish my php project.
Thanks

 
Comment by Thibaut Allender
2008-05-05 06:36:14

Good tips for the beginners.
About variable variables, you can also use concatenation :

$test = ‘blah’;
${$test.’2′} = ‘bloh’;
echo $blah2 // outputs ‘bloh’

 
Comment by Krzychu Danek
2008-05-09 00:33:56

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.

 
Comment by Jonas
2008-05-11 04:27:30

Why people use comparison with boolean constants?
$test == true does the same as just $test while $test == false is equivalent to !$test.

 
Comment by warren
2008-05-13 13:00:19

Jonas: That also baffles me. I guess it takes into account data types etc as well.

 
Comment by mallyone
2008-06-11 16:27:08

You caught me on a couple there! :)

 
Comment by php-web-developer
2008-06-24 03:03:08

Pretty cool!!!!!!!!!!!!!!!

 
2008-07-18 22:31:48

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.

Comment by David Jeffries
2008-07-18 22:36:54

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

 
 
2008-07-19 06:42:38

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.

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post