w3resource logo


PHP Tutorial

11 new features of PHP 5.4

Secondary Nav

Preface

PHP 5.4 has a wide range of new features added. This is a tutorial from w3resource to discuss them.

Support for traits has been added

A trait allows a developer to rescue codes, specifically saying, sets of methods, in many different independent classes, even if, those classes belong to different class groups. PHP 5.4 introduces Traits in PHP.

This, actually helps a developer to get rid of the limitation imposed by single inheritance nature of languages like PHP. Unlike languages of multiple inheritance, here, a class may only inherit from one particular parent class. But using Traits, developers may obtain characteristics from classes of different origin.

A trait, unlike class, can not represent itself. It's potential lies in the application of class members minus inheritance.

A good example of using PHP Traits can be found at PHP-Events project. Following code is an example of how it is used.

Usage

class MyClass {
    use Events;
}

Since, php-event is Trait based, every class can implement the event system as above. The following code shows a real code example.

$class = new MyClass();
$class->bind("hello", function($name) {
    echo "hello " . $name;
});
$class->trigger("hello", "Peeter");

Short Array syntax is added

Till PHP 5.3, Arrays are declared like following:

<?php
$array = array(
    "fname" => "Raja",
    "lname" => "Ram",
);
?>

In PHP 5.4, you may replace "array()" with "[ ]", like following, while declaring an array

<?php
$array = [
    "fname" => "Raja",
    "lname" => "Ram",
];
?>

This is a syntactical improvement which reduces the code size.

Function array dereferencing is added

Instead of this in PHP 5.3

<?php
function animals () {
  return array('t' => 'tiger', 'd' => 'deer');
}
 
$animals = animals();
echo $animals['t'];
?>

in PHP 5.4, you may use

<?php
function animals () {
  return array('t' => 'tiger', 'd' => 'deer');
}
 
echo animals()['t']; // prints tiger
?>

Closures can have $this keyword

Closures are objects that saves the scope that there is at creation time. In PHP, it resembles Anonymous Functions. As of PHP 5.4, you can use $this keyword in Closures. Following example shows how to use $this keyword.

<?php
class P {
  private $value = 10;
  public function getClosure() 
  {
    return function() { return $this->value; };
  }
}

$q = new P;
$fn = $q->getClosure();
echo $fn(); // prints 10
?>

Short open tag is available out of the box

In PHP 5.3, <?php //code here ?>, if you want to use short open tag, like <? //code here ?>, you had to make changes in the short_open_tag directive of php.ini file. But no more. In PHP 5.4, you can use short open tags without making any changes as you had to do.

Class member access on instantiation

If you have a code something like this

<?php
class Student
{
    function __construct($name)
    {
        $this->name = $name;
    }

    public function hello()
    {
        return "Hi " . $this->name;
    }
}
?>

The old way of instantiation is

<?php
$student = new Student("Amol");
echo $student->hello();
?>

In PHP 5.4 though, you may do it like

<?php
echo (new Student("Amol"))->hello();
?>

New way to invoke static functions

PHP 5.4 allows you to store the function name in a variable (as a string) and place that variable within the curly brackets. Consider a code like following

<?php
class Play
{
	class static function play_something()
	{
		echo "Playing!!"
	}

}
Play::{'play_something'}()
?>

So you define a class, and a static function within it, and then, you can just write the name of the function as a string like className::{'name of the static function as a string'}().

Binary number format is added

In PHP 5.4, you can use Binary data format. The following code shows an example.

<?php
$p = 0b1101 //must start with 0b and then you may write 1s and 0s, this is 13
$q = 0b1010 //9
$and_operation = $p & $q // for each bit and operation is performed
echo $and_operation; // prints 8 (binary 1000)
?>

Upload progress of files can be tracked by SESSION

Enable session.upload_progress.enabled in php.ini and you can now track upload progress of individual files being uploaded.

When a file is being uploaded, the upload progress will be available in the $_SESSION superglobal.

This is useful when used with XHR. Because, since you can now track the upload progress, you may send a POST request to using XHR and do some useful stuff.

Following code shows how you may implement this.

<form action="uploading.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

web server in Command Line Interface mode

This may be the most exciting one. PHP 5.4 allows you to start web server form command line.

Make sure that you have installed PHP 5.4 on your system. If you are running any other web server, also make sure that you stop that or you run it on a port other than 8000, which is the default port when you run web server from PHP.

Then you may start PHP's built in web server with the following command:

$php -S localhost:8000 -t /var/www

-t is optional, you may use it to define the document root of your web server. Otherwise, user's home directory will be the document root.

This is a screen shot taken on a Ubuntu 12.04 system

php cli web server starting

Now you may access the PHP (or HTML) file from this web server by pointing your browser to the file you want to execute.

PHP 5.4 also has improved parse error messages and incompatible arguments warnings.

Conclusion

Since it's inception, PHP has come a long way. With several new features added in PHP 5.4, it definitely took another leap. We encourage you to play around with these new features and share you experience.



Join our Question Answer community to learn and share your programming knowledge.