PHP 5.4.0 in a nutshell


Although purists have always sneered upon PHP for being a “patched” language; the evolution of PHP over the years, with new features added in every version, has only increased its popularity. The latest 5.4 release has followed the trend with some major feature additions. The following post describes some important changes in PHP 5.4.

Arrays

Arrays are one of the important elements of any programming language. Although PHP’s support of arrays is good, I had always found the ‘array’ constructor to be an eye sore. PHP 5.4 finally gets the short array syntax, available in most other modern languages. So now we can ditch the ‘array’ constructor and initialize arrays like the following.

$colors = ["blue", "green", "red"];
 
$items = ["monitors" => 3, "laptops" => 6];

The old syntax with the ‘array()’ constructor is obviously preserved, the above being a syntactic sugar for the old one.

Built-in Web Server

The CLI SAPI provides a built-in web server for development purposes – extremely helpful to quickly start testing your php pages. Just enter the following on the command line and you are ready to go. The server will now be listening to your requests on port 8000.

php -S localhost:8000

Which will display the following:

PHP 5.4.0 Development Server started at Fri Apr 06 13:56:26 2012
Listening on localhost:8000
Document root is C:\php-5.4.0
Press Ctrl-C to quit.

Of course don’t expect something along the lines of Apache or IIS. This is a small built-in service that lets you quickly check your pages. Absolutely not recommended to use on a production basis.

Binary data type added

A binary type has been added to make it easier to write code where you need to perform a great deal of bit twiddling.

$num_bin_a = 0b10010110; # decimal 150
$num_bin_b = 0b11001;    # decimal 25

echo $num_bin_a - $num_bin_b; # returns 125

Function Array Dereferencing

PHP now supports array dereferencing directly from a function call. Prior to version 5.4 you had to store the returning value from a function into a variable, and then use the variable.

The most frequent uses will be when using ‘preg_match’ or ‘explode’ kind of functions, functions that return an array. So instead of the following:

$data  = "piece1 piece2 piece3 piece4";
$pieces = explode(" ", $data);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

We could instead shorten this to:

$data  = "piece1 piece2 piece3 piece4";
echo explode(" ", $data)[0];

Another example using the ‘getdate()’ function.

# Without Function Array dereferencing 
date_default_timezone_set('Asia/Kolkata');
 
$temp = getdate();
 
echo $temp['year'];
echo $temp['mon'];
# With Function Array dereferencing 
date_default_timezone_set('Asia/Kolkata');
 
echo getdate()['mon'];

You can use the above in a conditional as shown below:

date_default_timezone_set('Asia/Kolkata');
 
if(getdate()['mon'] == 4) {
    echo "Month of April";
}

Another example using a custom function.

function getColors () 
{
  return [
          'red' => '#FF0000', 
          'green' => '#00FF00', 
          'blue' => '#0000FF'
         ];
}
 
echo getColors()['green']; // returns #00FF00

Code reuse using Traits

Traits enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. PHP being a single inheritance language, traits enables horizontal composition of behavior – the application of class members without requiring inheritance. I’ll cover Traits in a separate post itself. Below is a artificial example from the PHP documentation.

<?php
 
trait Hello 
{
    public function sayHello() 
    {
        echo 'Hello ';
    }
}
 
trait World 
{
    public function sayWorld() 
    {
        echo 'World';
    }
}
 
class MyHelloWorld 
{
    use Hello, World;
    public function sayExclamationMark() 
    {
        echo '!';
    }
}
 
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
 
?>

Which will output:

Hello World!

Tracking the progress of uploaded files

A long overdue feature; PHP now enables you to track the status of your file uploads. This requires that you enable the ‘session.upload_progress.enabled’ INI option. During a file upload an application can send a POST request to a separate endpoint (via Ajax for example) to check the status. The upload progress will be available in the $_SESSION superglobal when an upload is in progress

Misc. Core changes

Along with the above mentioned additions, a variety of new functions and additional methods to existing classes have been added.

Classes now support the Class::{expr}() syntax. Now you can accomplish something like the following for static calls:

class Test
{
    public static function parseH4()
    {
        echo "H4 Parsed";
    }
 
    public static function parseH2()
    {
        echo "H2 Parsed";
    }
 
}
 
$t = new Test;
$method_prefix = "parse";
 
$t::{$method_prefix . "h4"}();
$t::{$method_prefix . "h2"}();

Although not a very creative use of the idea, the real power of the above will manifest itself when using dynamic method calls. Along with the support for expressions while calling static class methods, class member access on instantiation has also been added, as shown below.

class Test
{
    public function SayHello()
    {
        echo "Hello World!";
    }
}
 
(new Test)->SayHello();

Magic quotes has been completely removed. Applications dependent on this feature may need to be updated, to avoid security issues. get_magic_quotes_gpc() and get_magic_quotes_runtime() now always return FALSE. set_magic_quotes_runtime() raises an E_CORE_ERROR level error.

The following functions have been removed from PHP 5.4, so if you are developing any new applications which will probably be migrated to PHP 5.4, avoid using the following functions.

define_syslog_variables()
import_request_variables()

session_is_registered()
session_register()
session_unregister()

mysqli_bind_param()
mysqli_bind_result()
mysqli_client_encoding()
mysqli_fetch()
mysqli_param_count()
mysqli_get_metadata()
mysqli_send_long_data()
mysqli::client_encoding()
mysqli_stmt::stmt()

The register_globals and register_long_arrays php.ini directives have been removed. Safe mode also is no longer supported. Any applications that rely on safe mode for security reasons may need adjustment. This feature had already been deprecated as of PHP 5.3.0 and is now completely removed. This will now generate a fatal E_CORE_ERROR level error when enabled.

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

4 Responses

1

Rod Elias

April 9th, 2012 at 8:09 am

Great post my friend. PHP is getting better each release.

2

Avinash

April 10th, 2012 at 8:11 pm

Have a look at this complete list of features included in PHP 5.4
http://www.xpertdeveloper.com/2012/03/new-features-php-5-4/

3

George Dina

April 12th, 2012 at 11:47 am

The Traits are fantastic feature.
Array dereferencing is also cool but I don’t know if I can get used with it.

4

vimal

April 15th, 2012 at 9:21 pm

This seems very cool.
will get power to code like java , javascript and something more…

Traits is an amazing feature that i would like to use to… It will have a remarkable impact on large scale applications……

Your thoughts