PHP 5.4 is Here! What You Must Know

PHP 5.4 is Here! What You Must Know

Tutorial Details

PHP 5.4 is here; the next major step forward since version 5.3 – keeping PHP 6 (full Unicode support) on hold for now. The latest enhancements significantly improve its elegance, while removing deprecated functionality, resulting in a dramatic optimization of the runtime (up to 20% more speed and memory usage reduction).

brace yourself

New Features and Improvements

Some of the key new features include traits, a shortened array syntax, a built-in webserver for testing purposes, use of $this in closures, class member access on instantiation, <?= is always available, and more!

PHP 5.4.0 significantly improves performance, memory footprint and fixes over 100 bugs. Notable deprecated/removed features include register_globals, magic_quotes (about time) and safe_mode. Also worth mentioning is the fact that multibyte support is enabled by default and default_charset has been changed from ISO-8859-1 to UTF-8.

Content-Type: text/html; charset=utf-8 is always sent; so there’s no need to set that HTML meta tag, or send additional headers for UTF-8 compatibility.


Traits

The best demonstration of traits is when multiple classes share the same functionality.

Traits (horizontal reuse/multiple inheritance) are a set of methods, which are structurally similar to a class (but can’t be instantiated), that can enable developers to reuse sets of methods freely in several independent classes. Because PHP is a single inheritance language, a subclass can inherit from only one superclass; that’s where traits come to play.

The best use of traits is demonstrated when multiple classes share the same functionality. For instance, imagine that we are building some website, and need to use both the Facebook and Twitter APIs. We build two classes which, in common, have a cURL wrapper function/method. Instead of performing the classic copy & paste of that method – to be used in two classes – we use Traits (copy & paste, compiler style). This way, we make reusable code, and follow the DRY (Don’t Repeat Yourself) principle.

Here’s an example:

/** cURL wrapper trait */
trait cURL
{
    public function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}

/** Twitter API Class */
class Twitter_API
{
    use cURL; // use trait here
    public function get($url)
    {
        return json_decode($this->curl('http://api.twitter.com/'.$url));
    }
}

/** Facebook API Class */
class Facebook_API
{
    use cURL; // and here
    public function get($url)
    {
        return json_decode($this->curl('http://graph.facebook.com/'.$url));
    }
}
$facebook = new Facebook_API();
echo $facebook->get('500058753')->name; // Rasmus Lerdorf

/** Now demonstrating the awesomeness of PHP 5.4 syntax */
echo (new Facebook_API)->get('500058753')->name; // Rasmus Lerdorf
$foo = 'get';
echo (new Facebook_API)->$foo('500058753')->name; // and again, Rasmus Lerdorf
echo (new Twitter_API)->get('1/users/show.json?screen_name=rasmus')->name; // and yet again, Rasmus Lerdorf
// P.S. I'm not obsessed with Rasmus :)

Got it? No? Here is the simplest example!

trait Net
{
    public function net()
    {
        return 'Net';
    }
}

trait Tuts
{
    public function tuts()
    {
        return 'Tuts';
    }
}

class NetTuts
{
    use Net, Tuts;
    public function plus()
    {
        return '+';
    }
}

$o = new NetTuts;
echo $o->net(), $o->tuts(), $o->plus();
echo (new NetTuts)->net(), (new NetTuts)->tuts(), (new NetTuts)->plus();

If you have any question about traits, please post a note in the comments section below.

Important Tip: The magic constant for traits is __TRAIT__.


Built-in CLI Web-Server

In web development, PHP’s best friend is Apache HTTPD Server. Sometimes, though, it can be overkill to set up httpd.conf just to use it within a development environment, when you really need tiny web server that can be launched with a simple command line. Thankfully, PHP 5,4 comes with a built-in CLI web server.

The PHP CLI web server is designed for developmental purposes only, and should not be used in production.

Note: The instructions below are for a Windows environment.

Step 1 – Create Document Root Directory, Router File and Index File

Go to your hard drive root (assuming C:\). Create a directory/folder, called public_html. Create a new file within this folder, and name it router.php. Copy the contents below, and paste it into this newly created file.

<?php
// router.php
if (preg_match('#\.php$#', $_SERVER['REQUEST_URI']))
{
    require basename($_SERVER['REQUEST_URI']); // serve php file
}
else if (strpos($_SERVER['REQUEST_URI'], '.') !== false) 
{
    return false; // serve file as-is
}
?>

Now, create another file, called index.php. Copy the contents below and save the file.

<?php
// index.php
echo 'Hello Nettuts+ Readers!';
?>

Open your php.ini file (it is located in the PHP install directory – e.g. C:\php).

Find the include_path settings (it is located at ~708th line). Add C:\public_html to the end of the string between quotes, separate by a semicolon. The final result should look like:

include_path = ".;C:\php\PEAR;C:\public_html"

Save and close the file. On to next step.

Step 2 – Run Web-Server

Open the command prompt (Windows + R, type in cmd, hit Enter); you should see something like this, depending on your Windows version.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\nettuts>

Change your current directory to the PHP installation by following the example below:

C:\Documents and Settings\nettuts>cd C:\php
C:\php>

Here comes the most important part – running the web-server. Copy…

php -S 0.0.0.0:8080 -t C:\public_html router.php

… and paste it in the command prompt (right mouse button, click Paste to paste). Hit Enter. If all goes well, you should see something similar to what’s shown below. Do not close the command prompt; if you do, you will exit the web-server as well.

C:\php>php -S 0.0.0.0:8080 -t C:\public_html router.php
PHP 5.4.0 Development Server started at Fri Mar 02 09:36:40 2012
Listening on 0.0.0.0:8080
Document root is C:\public_html
Press Ctrl-C to quit.

Open up http://localhost:8080/index.php in your browser and you should see:

Hello Nettuts+ Readers!

Voila! That’s it, happy coding!

Tip 1: Make a php-server.bat file with the following contents: C:\php\php -S 0.0.0.0:8080 -t C:\public_html router.php. Double click it, and, now, the server is up and running!

Tip 2: Use 0.0.0.0 instead of localhost if you anticipate that your server will be accessed from the internet.


Shorter Array Syntax

PHP 5.4 offers a new shorter array syntax:

$fruits = array('apples', 'oranges', 'bananas'); // "old" way

// The same as Javascript's literal array notation
$fruits = ['apples', 'oranges', 'bananas'];

// associative array
$array = [
    'foo' => 'bar',
    'bar' => 'foo'
];

Please note that “old” method is still in use and always will be. This is simply an alternative.


Array Dereferencing

No more temporary variables when dealing with arrays!

Let’s imagine that we want to retrieve the middle name of Alan Mathison Turing:

echo explode(' ', 'Alan Mathison Turing')[1]; // Mathison

Sweet; but it wasn’t always this easy. Before 5.4, we had to do:

$tmp = explode(' ', 'Alan Mathison Turing');
echo $tmp[1]; // Mathison

Now, what if we want to get the last name (last element in array):

echo end(explode(' ', 'Alan Mathison Turing')); // Turing

This works fine, however, it will throw a E_STRICT (Strict Standards: Only variables should be passed by reference) error, since it became part of E_ALL in error_reporting.

Here’s a slightly more advanced example:

function foobar()
{
    return ['foo' => ['bar' => 'Hello']];
}
echo foobar()['foo']['bar']; // Hello

$this In Anonymous Functions

this is anonymous functions

You can now refer to the object instance from anonymous functions (also known as closures) by using $this.

class Foo
{
    function hello() {
        echo 'Hello Nettuts!';
    }

    function anonymous()
    {
        return function() { 
            $this->hello(); // $this wasn't possible before
        };
    }
}

class Bar
{
    function __construct(Foo $o) // object of class Foo typehint
    {
        $x = $o->anonymous(); // get Foo::hello()
        $x(); // execute Foo::hello()
    }
}
new Bar(new Foo); // Hello Nettuts! 

Note that this could be achieved prior to 5.4, but it was overkill.

    function anonymous()
    {
        $that = $this; // $that is now $this
        return function() use ($that) {
            $that->hello();
        };
    }

<?= is Always On

Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:

<?=$title?>

…in your templates instead of…

<?php echo $title ?>

Binary Number Representation

binary php

There are only 0b10 kinds of people;
those who understand binary and those who don’t.

From now on, integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation, precede the number with 0x. To use binary notation, precede the number with 0b.

Example: representation of number 31 (decimal).

echo 0b11111; // binary, introduced in PHP 5.4
echo 31; // duh
echo 0x1f; // hexadecimal
echo 037; // octal

Callable Typehint

wuts dat

Typehinting is for those who desire to make PHP a stronger typed language. Type Hints can only be of the object and array type since PHP 5.1, and callable since PHP 5.4. Traditional type hinting with int and string isn’t yet supported.

function my_function(callable $x)
{
    return $x();
}

function my_callback_function(){return 'Hello Nettuts!';}

class Hello{static function hi(){return 'Hello Nettuts!';}}
class Hi{function hello(){return 'Hello Nettuts!';}}

echo my_function(function(){return 'Hello Nettuts!';}); // anonymous function
echo my_function('my_callback_function'); // callback function
echo my_function(['Hello', 'hi']); // class name, static method
echo my_function([(new Hi), 'hello']); // class object, method name

Initialized High Precision Timer

$_SERVER['REQUEST_TIME_FLOAT'] has been added, with microsecond precision (float). This is useful when you need to calculate the execution time for a script.

echo 'Executed in ', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2), 's';

__destruct() (or Summary)

Overall, PHP 5.4 offers numerous improvements. Now, it’s up to you to grab a fresh copy from php.net, and make quality Object-Oriented PHP code!

What do you think PHP 5.5 will bring us, and what do you expect?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.t-fox.nl Bas Tuijnman

    What’s the advantage of traits over just simply extending classes? I know traits are just a collection of methods, so maybe it would be handy for very basic functions like string sanitizing, but I don’t really see the point of it.

    • http://www.skyrocket.be Chris Ramakers

      It solves the single-inheritance problem that php has since it introduced OOP, read the introduction at http://be2.php.net/manual/en/language.oop5.traits.php which explains the use of traits over extending classes.

    • http://evansofts.com Evanxg

      The traits might not be useful for fanatical people of OOP, but they are time when making inheritance is just to much . remember that inheriting a class bring all the garbage from the parent you might not need and sometimes require to satisfy all the boiler code like abstract method implementation.
      trait can be a collection of method groupe togheter for many uses and since they are enclose in a named type , you code still is very orginised (e.i they act like namespace) .
      A wonderful language that has this feature is C++ (it’s called friendship between class and function) .

    • http://benmartinstudios.com.au Ben

      The real advantage of traits is that a class can use multiple different traits. In PHP, a class that you make can only extend one other class, whereas traits try and address that by allowing you to “use” multiple traits and then choose which one takes precedence.

      • Willian

        Traits seems to be a maintenance nightmare when you use class members in it …

    • Gerard van Helden

      You shouldn’t regard traits as multiple inheritance, because that would imply that it is a typing mechanism in OO. That isn’t really what it is useful for though, it is most useful for behaviour that is common to classes regardless their type. Think of generic __toString() implementations, for example. Any method that you would normally copy/paste now can be “mixed in”, without the hassle of introducing useless “mother of all types” classes or bothering with weird adapter classes.

    • Jack

      Traits can be composed of other traits… this allows encapsulating specific use cases by introducing just the exact collection of traits needed for each use case at runtime. Furthermore when the traits’ functions are used they are treated as part of the object into which they’re introduced, so unlike w/ straight injection, the introduced traits’ functions have direct access to the variables belonging to $this. Dependencies are not as obviously visible as when they’re injected at instantiation, but they’re still easy to find in the class declaration. Also utility-type functions such as file io etc. can be easily introduced where needed without resorting to singletons or other global flotsam.

  • http://artatm.com Rocky

    Finally <?= becomes a normal feature and not something that needs to be set!!!

  • Mark

    For those of you using SQL Server with PDO as your database connection of choice DO NOT UPGRADE.

    The SQLSRV PDO driver is not currently compatible with PHP 5.4. There is an RC that has been posted in the usergroup but I’m not sure if this has been accepted as bug free.

    • http://www.dahlladesigns.com lande

      Thats a sad news.

      • http://www.hackingproductivity.com Chris

        Agreed!

  • http://khaledgarbaya.net Khaled

    PHP 5.4 rocks (<?=) oh Finally !

  • http://www.prisonofmirrors.com Prison of Mirrors

    Finally it’s released! There are some cool new features and the reduced memory usage is always a good thing. Also that’s pretty neat with the built-in web server. Now if only I can convince my work to upgrade…

  • http://blog.mostof.it/ Ochronus

    Nice list of changes, thanks!

    For those who wish to know about changes in php 5.3, see http://blog.mostof.it/whats-new-in-php5

  • jm

    A lot of features from ruby / python / js :-)
    Great !

  • http://wpden.net/ Ritesh Sanap

    latest PHP version have lot of improvements, i really liked the direct echo or Array without assigning a Variable

  • http://eire32designs.com/ Eire32

    Fantastically written article. Great use of memes by the way. Good examples and points. Hope to see more of your articles soon.

  • Devin Dombrowski

    Hurray for Array Dereferencing.

    I always thought it was so annoying to write two lines just to get at one little value.

  • http://www.sofwan.net sofwan

    Thank you for the article. Shorter array syntax is interesting so other improvements and new features. For next PHP version, 5.5. I hope already include xdebug inside.

  • austin

    FINALLY!!! binary constants, lines like this will no longer be needed:

    $firstMask= bindec(“10000000″);

    i find all bitops look nicer and are easier to understand when they are displayed in binary
    320 |
    256
    ——-
    320
    vs
    101000000 |
    100000000
    —————
    101000000
    720 |
    256
    ——
    976
    vs
    1011010000 |
    0100000000
    —————–
    1111010000

    in decimal the pattern isn’t obvious to a novice (one number | 256 yeilded the first number, a different number | 256 seemed to sum each of the decimal place) while in binary its clear (they were combined with the 1′s replacing 0′s where applicable)

    of all the changes mentioned binary constants is the one im most excited for.

  • http://webtekmedia.com/ Jack

    Any hosting that will or already has support for PHP 5.4??

    • http://www.jeffrey-way.com Jeffrey Way

      Not that I know of. Anyone?

    • webarto
      Author

      Probably won’t be anytime soon (shared hostings). They haven’t updated to 5.3.10 which fixes major security vulnerability. PHP 5.4 will break “backwards compatibility” (safe_mode, magic_quotes, default charset UTF-8), and they would have trouble explaining to their customers what and why. Get a VPS :)

    • http://returnwt.net returnWT

      My website (which is on shared hosting), runs on PHP 5.3.9, so there are webhosts actually using newer versions of PHP ;) (Hosted by bigwetfish.co.uk, awesome company, just need to ask to get moved to a 5.3 server and it’ll be done within about 24 hours)

    • said

      try this my.phpcloud.com

  • http://www.w3sanju.in Sanju

    Great news !!

  • http://www.cyberstream.us Eli Mitchell

    Woohoo! Excellent intro overview of PHP 5.4. I’m so happy for all these new features, especially the new array constructor syntax and anonymous functions.

  • http://web.tursos.com Josue Ochoa

    Brace your selves, memes are coming!

  • Leonel

    Waiting for it to be available at ubuntu repositories!

  • Napstyr Maceda

    PHP 5.4 makes the code more flexible and Rock!!

  • http://richiepearce.com Richie

    Although syntactically clean, I do not see a requirement for traits. One would need a place to store them which unless it was a class might feel like a lose end?

  • alex

    Veeery nice,
    too bad that services like rackspace are still using versions like 5.2.. =(

  • Mahbubur Rahman

    Really Cool !

  • http://hivomark.com Hieu Vo

    How about built-in APC?

  • http://freshlybakedwebsites.net Barry Hughes

    All changes for the better so far, exciting times.

    I’d like to see more complete (optional) type-hinting for future versions – and op-code caching as standard would be fantastic.

    • http://freshlybakedwebsites.net Barry Hughes

      Actually, what about C# style properties as a further alternative to the current getter/setter syntax? It can make for some nice clean code.

      • andrew

        oh god please no, I hate that C# syntax. (for no particular reason) :)

  • Evanxg

    Please , how do you make this works
    this has never worked for me . calling method on a newly instaciated object

    echo (new NetTuts)->net() ;

    I always have to create a temporary variable of create a wrapper function

    • http://www.cyberstream.us Eli Mitchell

      It has never worked in PHP before. I think this is one of the new features PHP 5.4. Very useful!

    • http://mbriedis.id.lv/ Briedis

      This is easily done if you have a factory method. For example: $foo = Class::instance()->doStuff();
      Goes together with singletone pattern nicely.

  • http://www.web4you.co.in Deven CK

    Nice explanation, PHP is rocking day by day ..

  • http://www.xpertdeveloper.com Avinash

    For traits have a look at this article: http://www.xpertdeveloper.com/2011/11/trait-in-php/

  • http://github.com/andrerom André R.

    > $this In Anonymous Functions

    Unless I have misunderstood this change, this section fails to mention the most important part of this change: access to private/protected methods/members, it is not just that you don’t have to do “$that = $this;” anymore.
    Also, looking at the doc of Closure, it seems (re)binding is now possible: http://php.net/closure

  • mehrdd

    NICE …
    i like new arrays !

  • Victor

    Traits are so weird :S another N reazons to confirm my love to JAVA

  • http://mezatech.com Amr Soliman

    Wow .. Great updates
    good playing with function and array

    $var = myfunction()[1];
    nice one

  • http://anarinfo.com/ Anaradam

    Great News!!!!!!!!!

  • http://www.pytania.biz Pytania

    New arrays are great!

  • Simon

    $processTemplate = \Closure::bind(function() { return $this; }, $presentationModel);

    HEEELLLLLOOOOOOO! :D

  • http://www.anil2u.info Anil Kumar Panigrahi

    New array concept is good.

  • mohammed tantash

    Wow new PHP version the most needed i guess feature is tracking of file uploads which has it’s share of headaches i actually wrote a blog post about :http://www.get-awebsite.com/blog/code/article/?PHP-File-Upload-Progress-Bars-4

  • http://www.techispeaks.com Kathirason

    Traits and shorter array are most welcome..

    • http://www.kezber.com Web Design

      Agreed, shorter arrays is welcome!! simplicity is always good!

  • Onkar

    Hi,

    In above mentioned example you have used traits in multiple classes.

    I can do this by creating static methods in a class and on using static method no object initiated.

    So I want to know the difference ?

  • http:///user/view/1016596 Edmond Smeal

    Good ¨C I should definitely say I’m impressed with your blog. I had no trouble navigating through all the tabs as well as related information. The site ended up being truly easy to access. Nice job…

  • http://www.pdvictor.com Peter Drinnan

    The thing that makes me most happy is the short_open_tags. I am so tired of arguing over that one with other developers who insist that

    is somehow better than

  • http://magpiewebsitesolutions.co.uk steve graham

    Hooray for session upload progress. There’s a quick look at how it works here. http://chemicaloliver.net/programming/php-5-4-file-upload-progress-and-html5-progress-bars/

  • http://developerscentral.net/ somyadeep

    very useful information for PHP LOVER like me :)

  • http://yahavgindibar.com Yahav Gindi Bar

    Great summery, thanks :)

    BTW – you could use $this in anonymous functions in this way:

    $callback = function() use (&$this) {
    print $this->getTestVariable();
    };

  • Tyrion

    Still hate it.

  • http://claudiobonifazi.com Claudio

    I’m sorry, can someone explain to me the difference between $_SERVER['REQUEST_TIME_FLOAT'] and calling microtime(true) ?

    • Ulaş Özgüler

      REQUEST_TIME_FLOAT is the timestamp of START of the request, microtime returns CURRENT timestamp. So microtime – request_time_float = execution time in milliseconds.

  • slier

    (new NetTuts)->net() //constructor return itself…hell yes no more temp variable for method chaining

  • Vedant

    How Can We Use date(); function in php 5.4 without getting any error

    Please explain in detail ….

    • Jack

      Default time zone has to be set with date_default_timezone_set(), as in date_default_timezone_set(‘America/Denver’); can be done at beginning of scripts or in php.ini but there are also other places to set it as well.

  • maltray

    Is there any book you guys recommend for PHP 5.4?

    I would appreciate that!, thanks :)

  • marcos

    muy avanzado para mi gusto gracias igual

  • http://www.euperia.com Andrew McCombe

    Excellent guide to the new features in PHP 5.4. I’ve been using the built-in webserver whilst developing and found it very useful. Traits are something that has the potential to be overused but it’s still a very useful feature.

    Thanks!

  • http://www.facebook.com/profile.php?id=1076928285 CJ Corona

    PHP 5.5 will allow us make robots