Some PHP Abilities You May Not Know About

April 4th, 2008  | Tags:

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.

  1. April 5th, 2008 at 23:08
    Reply | Quote | #1

    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.

  2. April 6th, 2008 at 05:29
    Reply | Quote | #2

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

  3. April 6th, 2008 at 10:26
    Reply | Quote | #3

    Thanks Joey, I never knew it was called that

  4. Garr
    April 6th, 2008 at 12:14
    Reply | Quote | #4

    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.

  5. Audigex
    April 6th, 2008 at 16:17
    Reply | Quote | #5

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

  6. April 6th, 2008 at 16:32
    Reply | Quote | #6

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

  7. DGM
    April 7th, 2008 at 06:57
    Reply | Quote | #7

    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?

  8. DGM
    April 7th, 2008 at 06:59
    Reply | Quote | #8

    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?

  9. Octopus
    April 7th, 2008 at 20:55
    Reply | Quote | #9

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

  10. April 8th, 2008 at 22:01

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

  11. April 10th, 2008 at 13:12

    There’s no ternary operator in Java?

  12. April 10th, 2008 at 13:22

    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.

  13. April 11th, 2008 at 08:41

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

  14. April 13th, 2008 at 01:02

    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.

  15. April 18th, 2008 at 08:30

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

  16. April 22nd, 2008 at 02:42

    argh!

    This is bad:

    It should be

  17. April 22nd, 2008 at 18:07

    Some interesting PHP tips, thanks for sharing.

  18. April 24th, 2008 at 11:17

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

    Thanks!!

  19. April 28th, 2008 at 15:04

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

  20. May 5th, 2008 at 06:36

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

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

  21. May 9th, 2008 at 00:33

    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.

  22. Jonas
    May 11th, 2008 at 04:27

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

  23. warren
    May 13th, 2008 at 13:00

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

  24. Adamz
    May 21st, 2008 at 09:14

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

  25. mallyone
    June 11th, 2008 at 16:27

    You caught me on a couple there! :)

  26. Adam
    June 16th, 2008 at 19:42

    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.

  27. June 24th, 2008 at 03:03

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

  28. July 18th, 2008 at 22:31

    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.

  29. July 18th, 2008 at 22:36

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

  30. July 19th, 2008 at 06:42

    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.

  31. October 9th, 2008 at 12:06



    echo $test == true ? "is true!" : "not true";


    you made my day! You really gave me a good laugh with this stuff … : )

    Sorry back to business. Maybe it would be good to wrap all these things up and create yet another PHP beginners tutorial : )

    Don’t want to sound sarcastic here though… these small flakes of wisdom combined with some milk of clearness poured in a bowl of guidance could provide a great breakfast for the starting PHP scripters out there ; )

    greetz

    rico

  32. October 9th, 2008 at 12:18

    or even


    <div class="">
    ...

    and off you go

  33. October 9th, 2008 at 12:21

    hmmm … again …

    <div class="<?= $selected ? ’selected’ : ” ?>">

    </div>

    do not want code strippin comment form …

  34. October 9th, 2008 at 15:42

    Or how about:

    $class = $selected ? ’selected’ : ”;

    The ternary operator may be clearer if you use parens:

    $class = ($select ? ’selected’ : ”);

    The argument that it isn’t clear or hard to understand only makes sense if you don’t know the language. $x = $x + 1; is not clear to my ten-year-old, but a programmer should recognize the operators and idioms of their language on sight.

  35. October 9th, 2008 at 15:58

    All of these arguments are pretty much canards.

    The one line of XHTML that gets stuck in the PHP parser can be emitted by PHP. You can either give up on XHTML like the rest of the world has, or you can live with emitting this one line however “messy” that might be. The kind of programmer who feels nauseated with short open tags is usually the same kind of programmer who uses a separate template engine to generate output, and that solves the whole problem and gives you XHTML and MVC perfection.

    If you use an ISP that has short open tags turned off, turn it on in your .htaccess file. If your ISP doesn’t allow you to change any of the PHP runtime configuration they probably also have things like register globals and magic quotes turned on, so get a different ISP that gives you some control. I’ve built and deployed a lot (hundreds) of PHP web sites and have only ever run into ONE lame ISP that had short tags off and didn’t allow .htaccess overrides.

    If you are a big corporation and control your own servers and php.ini files, there’s no problem. If you’re a big corporation using outsourced managed hosting, and your server is shared with other users so you can’t control the PHP configuration, you’ve already made a huge mistake in your hosting decision. I have worked for lots of big companies and none of them use $9.95 GoDaddy accounts to run their web sites.

    If you are building a PHP application for widespread deployment, you might want to think about this a little. Most PHP apps are one-offs so this doesn’t apply to the majority of PHP developers. The few times that I’ve had to worry about this I’ve gone ahead and written with short open tags and the <?= shortcut, then scripted my text editor to replace all of those tags with <?php when I release. Problem solved.

  36. October 9th, 2008 at 16:04

    Nice articles. Every single one of these tricks are documented in the PHP online docs, so if you’re a PHP programmer getting paid to write PHP, and you don’t know about default function arguments or the ternary operator, you need to stop surfing the web for a while and visit php.net and read the annotated documentation. Just skim so you have some subconscious memory of the features.

    It’s not things like short open tags and “hard to read” ternary expressions that plague PHP code; it’s programmers who don’t know the language and are surprised by things they find in articles like this. More than half of the freelance work I get is rewriting crap PHP some freelancer copied from a book, so I’m very used to seeing the kinds of gyrations programmers go through to do things the language already does.

  37. GyratingProgrammer
    October 29th, 2008 at 13:54

    Greg Jorgensen :All of these arguments are pretty much canards.
    The one line of XHTML that gets stuck in the PHP parser can be emitted by PHP. You can either give up on XHTML like the rest of the world has, or you can live with emitting this one line however “messy” that might be. The kind of programmer who feels nauseated with short open tags is usually the same kind of programmer who uses a separate template engine to generate output, and that solves the whole problem and gives you XHTML and MVC perfection.
    If you use an ISP that has short open tags turned off, turn it on in your .htaccess file. If your ISP doesn’t allow you to change any of the PHP runtime configuration they probably also have things like register globals and magic quotes turned on, so get a different ISP that gives you some control. I’ve built and deployed a lot (hundreds) of PHP web sites and have only ever run into ONE lame ISP that had short tags off and didn’t allow .htaccess overrides.
    If you are a big corporation and control your own servers and php.ini files, there’s no problem. If you’re a big corporation using outsourced managed hosting, and your server is shared with other users so you can’t control the PHP configuration, you’ve already made a huge mistake in your hosting decision. I have worked for lots of big companies and none of them use $9.95 GoDaddy accounts to run their web sites.
    If you are building a PHP application for widespread deployment, you might want to think about this a little. Most PHP apps are one-offs so this doesn’t apply to the majority of PHP developers. The few times that I’ve had to worry about this I’ve gone ahead and written with short open tags and the <?= shortcut, then scripted my text editor to replace all of those tags with <?php when I release. Problem solved.

    Could you possibly sound more arrogant than this?

  38. GyratingProgrammer
    October 29th, 2008 at 13:55

    Greg Jorgensen :Nice articles. Every single one of these tricks are documented in the PHP online docs, so if you’re a PHP programmer getting paid to write PHP, and you don’t know about default function arguments or the ternary operator, you need to stop surfing the web for a while and visit php.net and read the annotated documentation. Just skim so you have some subconscious memory of the features.
    It’s not things like short open tags and “hard to read” ternary expressions that plague PHP code; it’s programmers who don’t know the language and are surprised by things they find in articles like this. More than half of the freelance work I get is rewriting crap PHP some freelancer copied from a book, so I’m very used to seeing the kinds of gyrations programmers go through to do things the language already does.

    Yes, apparently you can.

TOP