Category Archives: Tips

PHP 5.4 – 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!

PHP 5.4 – 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.

Read more »

PHP 5.4 – 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.