Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


PHP 5.4 Alpha 1 is here!

without comments

Three days ago, that is on 28-06-2011 the PHP 5.4 alfa 1 version was announced on ww.php.net!

Basically in this release are the things that were made for PHP 6 and did not make it in PHP 5.3, next to some other new features.

Some of the most interesting new features are:

Traits

A new OOP feature. Basically for horizontal code reuse, that is inheriting of methods instead of extending classes.

trait Inharitable {
    public function test() {
        echo 'Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . PHP_EOL;
    }
}

class A {
    use Inharitable;
}

class B {
    use Inharitable;
}

$a = new A();
$a->test(); //Class: Inharitable Method: Inharitable::test

$b = new B();
$b->test(); //Class: Inharitable Method: Inharitable::test

Traits in PHP 5.4 are the new namespaces of PHP 5.3, that is the most interesting feature in PHP 5.4.

Scalar type hinting

Up to PHP 5.3 there was type hinting only for classes, interfaces and arrays. With PHP 5.4 type hinting can be used for scalar data types like: int, string, float, book and resource.

function test(string $var) {
  echo $var;
}

$a = 'aa';
test($a);

Unfortunately on this alpha version on my computer I get: Catchable fatal error: Argument 1 passed to test() must be an instance of string, string given, called in .. on line 58 and defined in … on line 52

What can I say… it is still an alpha…

Closures

Yes, I know, there are closures in PHP 5.3 too, but there are not the same. In PHP 5.3 if you wanted a closure you had to use the keyword use and then specify the variables that the lambda functions will have access to.

In PHP 5.4 it’s beginning to look more like JavaScript, in a good way:

class closureTest {

    private $a;

    function test() {
        $this->a = 'object var';
        return function () {
            echo $this->a;
        };
    }
}

$a = new closureTest();
$b = $a->test();
$b(); // object var
unset($a);
$b(); // object var

Closure in the right way, with a lambda function the way it should be! Just like lambda functions existed even before PHP 5.3, but only after the new syntax they’ve become popular, now there was closures time.

This are some of the things that I find most interesting, but there are only a part of the new features that PHP 5.4 brings!

It’s likely that before the end of this year the final version will be ready.

I’m curious if with the final version of PHP 5.4 a new certification will come out, taking in consideration that the changes are not major.

Written by Claudiu Persoiu

1 July 2011 at 8:27 AM

Leave a Reply