in ,

PHP 5.4: You Must Know PHP 5.4 Features

It enhance its elegance and eventually results in a climactic optimization of its runtime i.e. fast speed enhanced by upto 20% as well as reduction in memory usage while eliminating the deprecated functionality.

New Features and Improvements

When the matter of things come to its new features and enhancement it incorporates trait S that is a shortened array syntax, for testing and analyzing purpose it has a built-in webserver, employment of $this in closures, <?= is available for all time towards class member access on instantiation and much more.

However, PHP 5.4 eventually enhance performance, fixes more than 100 bugs and memory footprint. The noticeable features which has been eliminated include safe_mode, register_globals as well as magic quotes (concerned to time). Moreover, it is worthy to add that the capability of multibyte support is accredit by default as well as default_charset has been transformed from ISO-8859-1 to UTF-8.


Traits (multiple inheritance/horizontal reuse) are considered as a series of some methods, which are referred as structurally identical to a class which lets the developers to re-employ the series of methods independently throughout the distinct independent classes. As PHP is a language of single inheritance, a subclass can access from only one superclass; and here traits come to play.

The best employment of trait is determined when the same functionality is shared by multiple classes. For example, suppose we are creating some website where we are required to employ Facebook and Twitter APIs both. Now, we have to built two classes where a common cULR wrapper method/function is to be used rather than of employing the classic method of copy & paste and should be employed in two classes – we use Traits i.e. copy & paste and compiler style. However, in this way we can achieve reusable code and perform DRY stands for Don’t Repeat Yourself principle.

Let’s see this illustration –

/** 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);
return $output;

/** Twitter API Class */
class Twitter_API
use cURL; // use trait here
public function get($url)
return json_decode($this->curl(''.$url));

/** Facebook API Class */
class Facebook_API
use cURL; // and here
public function get($url)
return json_decode($this->curl(''.$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 :)

Perhaps you got it, if not, take a look over this simple one –

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();

Built-in CLI Web-Server

In web development, Apache HTTPD Server is referred as the best friend of PHP. Even sometime it may exaggerated in context of setting up of httpd.conf just for making it enable to adapt in a development environment. In the case, when you literally required a tiny web-server which can be launched just in account of a simple command line. Thanks to PHP 5.4 features which has a built-in CLI web server.
Note: The below provided instruction are only for Windows environment.

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

First of all you are required to arrive at the root assuming C:\ of your hard drive. Next, create a folder or directory called as public_html. Now, create a new file as router.php within this folder. Paste the below provided content in the created file router.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

After accomplishing this, create an another file called index.php and save the file after pasting the below contents.

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

Now, you are required to open the php.ini file which sits in the PHP install directory.
Designate the include_path setting (you will find at ~708th line. Next add C:\public_html at the end of string between quotes and is separated by a semicolon. Eventually, you will got a result like this:

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

Now, you are supposed to save the file and close it as well as follow next step.

Step 2 – Run Web-Server

Here, open the command prompt by Windows+R and type in cmd then hit enter; However, on the ground of your Windows version, you may get something like this:

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

Now, you are required to transform your current directory to PHP installation with reference to this example provided below:

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

Now, the most significant part – running the web-server will appear. Therefore, copy and paste the below listed command prompt. When you performed successfully, something will appear on your screen as shown below. Here, don’t attempt to close the command prompt, otherwise you will exit the web-server as well.

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

Open up http://localhost:8080/index.php in the browser where you should see:

Hello Nettuts+ Readers!

However, take a look over this useful tips:

  • Create a php-server .bat file comprising the contents: c:\php\php -S -t C:\public_html router.php. To make the server up and running you are required to double click over it.
  • Use rather than of localhost in the case when you assume your server to be access through internet.

Shorter Array Syntax

PHP 5.4 provide a novice 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'

Point should be marked that this is referred as just an alternative. However, the “old method” is still in use and supposed to be always will be.

Array Dereferencing

When dealing with arrayS say no more temporary variables.

Let’s assume that you want to fetch the middle name of Alan Mathison Turing.

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

It was not so easy before PHP 5.4:

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

So, what in context of retrieving the last name i.e. last element in array:

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

It works good, however, it will convey an error a E_STRICT (Strict Standards which says that only variable should be passed by reference, since it became the part of E_ALL in error_reporting.

Take a look over this another advanced illustrtaiton:

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

$this In Anonymous Functions

Now, you can refer to object instance through anonymous functions i.e. also called as closures by employing $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!

Marked that it could be accomplished through earlier version of PHP i.e. PHP 5.4, but it was overstated.

function anonymous()
$that = $this; // $that is now $this
return function() use ($that) {

<?= is Always On

Apart of php.ini setting, short_open_tag, <?= (open PHP tag and echo) will be available for always and might be considered as quite safe to use <?=$title?> rather than of <?php echo $title ?>

Binary Number Representation

Perhaps, you would be acquainted that integers can be represented in decimal (base 10), octal (base 8), hexadecimal (base 16) or binary (base 2) notation and further can be preceded by symbols (+ or -) which is optional. However, in order employ octal representation, precede the number with a zero. In case of hexadecimal and binary notation precede the number with 0x and 0b respectively.

Let’s consider this example of representing number 31 (decimal) as example:

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

Callable Typehint

Typehinting is specifically useful for those who want to render PHP as a stronger typed language. Type Hints can be only of array and object type since PHP 5.1 as well as callable since PHP 5.4. Now, the type hinting of traditional type with string and int is not 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 also included with microsecond precision. It seems to be quite obvious when you are supposed to evaluate the execution time for a script.

echo ‘Executed in ‘, round(microtime(true) – $_SERVER[‘REQUEST_TIME_FLOAT’], 2), ‘s’;

However, PHP 5.4 congregates various enhancements and achievements that will verily proved as very beneficial and worthy for you.

What do you think?

Written by Admin

Nola J Arney is working as an application and web developer at HTMLPanda. Her core technical skill in web designing, Sencha touch, PhoneGap, and other platforms has contributed a lot of benefits to the business. She has an interest in writing and hence, she has written numerous blogs & articles that specifically shed a light on website the designing & development technology. All her write-ups have earned a gratitude from the specialists worldwide.


Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *





How to Create a Complete Excel Spreadsheet From MySQL

Best WordPress Photo Gallery & WordPress Gallery Plugins