Pressure is nothing more than the shadow of great opportunity. - Michael Johnson

How well do you know your preferred scripting language?

1 year, 8 months ago

Over the years I've used TCL and ASP extensively to build the back-end of a range of web sites as well as dabbling in frameworks like ASP.NET. In the last 4-5 years I've used PHP almost exclusively. Recently there's been a lot of interest around languages such as Ruby and Python and I've wondered on several occasions whether or not I ought to invest time in learning one of these. Python, mostly because of the Django Framework, interests me most. However I've been torn. Although on the surface learning a new language seems like it's mostly a syntax change, in reality I think it really takes time to properly understand the intricacies of each and, by spreading my time more thinly between multiple scripting languages, will I limit my chance to dive more deeply into the subtler features of PHP?

If, like me, you're into PHP here's 10 things you may or may not know about the language.

  1. PHP 5 introduced Fluent Interfaces (or as it's more commonly known in other languages - Method Chaining). Fluent Interfaces are a method for chaining methods of an object together. Each method returns a reference to $this, the object itself, and by doing so allows you to write statements like this:

    1. $sSql = $oDb->Select('title')->From('articles')->OrderBy('title asc')->Get();

    as opposed to this:

    1. $oDb->Select('title');
    2. $oDb->From('articles');
    3. $oDb->OrderBy('title asc');
    4. $sSql = $oDb->Get();

    Of course Fluent Interfaces aren't appropriate in all situations, but as in the example above, used correctly they can definitely make your code more readable.

  2. The relatively new filter library offers stock methods for validating and sanitising common types of data. You no longer need to write custom code to validate an email or IP address, for example.
  3. You can now specify that you want foreach loops to return values by reference. This is achieved by pre-pending the variable with the reference sign (&) and gives you the ability to modify values in the source array.

    1. foreach ($aData as &$sValue) {
    2. $sValue = "$sValue, ";
    3. }
  4. The improved MySql library supports running multiple queries in one hit with the mysqli_multi_query function. Simply separate queries with a semicolon. Of course use with care, without careful filtering of your input this command will make particularly nasty SQL injection attacks much easier.
  5. $_SERVER['PHP_SELF'] is often used to populate the "action" part of an HTML form as shown below:

    1. <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

    However what you may not know is that, without sanitising the content in this variable, you're leaving your site wide open to cross site scripting attacks (XSS). A better (although not necessarily full proof) approach in this situation might be:

    1. <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  6. PHP 5 allows you to define an autoload function which is automatically called if you try to reference a class which hasn't already been defined. This can be used to take care of including the right library files on the fly. For example if you include the following function within your code.

    1. function __autoload($sClassName) {
    2. require_once(strtolower($sClassName).'.inc.php');
    3. }

    and call

    1. $oDb = new Db();

    PHP will try to automatically include "db.inc.php" before trying to create an instance of the class. The autoload function can be declared anywhere in your code. I haven't tested the performance impact of this feature but I think the principle totally rocks. It offers massive opportunity to create plug and play code without the usual nightmare of managing a massive list of static includes.

  7. The Tidy extension offers a massive amount of functionality for parsing HTML documents such as iteration through nodes and returning those with specific ids.
  8. PHP supports variable variables. That is, a variable name which can be set and used dynamically based on data in another variable. For example if we assign a value to a new variable, $a:

    1. $a = 'hello';

    and then assign a value to a variable variable, $$a:

    1. $$a = 'world';

    in effect what we've really done is to create a variable named $hello which contains the value 'world'. At first glance this would seem to be a bit pointless but the ability to dynamically create variables like this based on data in your running application can be incredibly useful.

  9. Class methods can be called statically, that is without creating an instance of the class. This can be useful for creating groups of utility functions which are effectively namespaced without the need to create an instance of that class before using them.

    1. class Utility {
    2. public static function SanitiseComment() {
    3. ...
    4. }
    5. }
    6. $sComment = Utility::SanitiseComment($_POST['comment']);

    One thing to be aware of when calling methods statically - you can't reference the $this keyword as you're essentially working off the class definition itself, not an instance of that class.

  10. Lastly, and a good point to end on, PHP offers many ways to do the same thing. Choose your method wisely - some are more efficient than others. For example explode is more efficient than split for splitting a string as it doesn't use regular expressions.

So how many were you aware of? What interesting features or language constructs do you know that I might not have come across yet, and what's your take on diversifying versus learning one language really well? Post your thoughts below.

Comments

  • Great tips.... but there's one problem: ad 8, $aa is not variable variable.

    Dragan - 27th March 2007 #

  • Dragan - thanks for pointing out the typo. I've corrected accordingly.

    Ed Eliot - 27th March 2007 #

  • If you can spare the time, then definitely go for it and learn a new language!

    However after using Rails/Django for a bit, you probably will start to hate PHP ;)

    SmileyChris - 27th March 2007 #

  • Great stuff... especially the tip about static use of class methods.

    My current favorite piece of PHP goodness is the glob() function that allows you to get all the files/directories whose paths match a certain pattern.

    Much underused in my opinion! Most people seem to use the much more verbose opendir() and readdir() etc.

    Mark Perkins - 28th March 2007 #

  • Great post, Ed. I didn't know about the mysqli_multi_query function in point 4. Handy!

    Drew McLellan - 28th March 2007 #

  • Thank you - I enjoyed the collection of 'possible unknowns', and indeed I didn't know a couple of them. One of my recent discoveries is PDO's ->getColumnMeta() method that can allow something to look up information when it doesn't know about the table it's dealing with. A good match to this would be the Reflection classes - the ->getProperties() method can give you a list of properties for an unknown class or object.

    As to learning new languages, I'm in much the same boat - I use PHP almost exclusively, but recently started working with Python and can't say as I'd care to spend a lot of time learning it well, but don't regret the time I've spent thus far at all. It's a new view on things, and it's always handy to know a little in case you're thrown into using something unexpectedly.

    Jaciss - 14th May 2007 #

Help make this post better

Notes: Standard BBCode for links, bold, italic and code are supported. rel="nofollow" is added to all links. Your email address will never be displayed on the site.

Back to index