What is new in PHP 5.3 for PHP amateurs?

In a recent PHP conference in London some great speakers spoke about new features in PHP to be released in PHP 5.3. PHP 5.3 contains functionality that was scheduled for PHP 6, which takes PHP 5.3 from being a minor release to a significant and huge release. A release that no PHP developer should ignore. Most of these features are pretty complicated additions for novice PHP programmers. I have listed some features and some ways to use them.

1) Namespaces for classes and functions
This feature will help us shorten the class names and function names. To appreciate this feature, we need to go back to the days before there was Object Oriented Programming in PHP. Imagine all the function names with name save(). How would you differentiate if the call save() was to save a blogs or save comments? The solution was to use blog_save() or comment_save() before the introduction of classes in which we could write the save() function within the Blog class or the Comment class. Using classes is obviously a much more elegant solution.

We now have the same situation with the large number of classes and functions. Using namespaces, we could simply separate the two functions above in the code below:

<?php
namespace Blog;
function save()
{
echo "Now saving the blog!";
}

namespace Comment;
function save()
{
echo "Now saving the comment!";
}

// To invoke the functions
Blog\save();    // This prints - Now saving the blog!
Comment\save(); // This prints - Now saving the comment!
?>

EDIT: A final decision was made on October 2008.  Developers will have to use \ backslash operator to dereference namespaces.

2) MySQL Native Driver
PHP 5.3 has a native driver specific to PHP, optimised for the ZEND engine. It is an alternative to connect to MySQL server versions newer than 4.1. Being a native driver we should be able to get much faster execution times. The native driver will also be licensed under the PHP license. If you are like most users, you are currently using libmysql (A MySQL database client library) you will be able to easily switch over to mysqlnd without making any changes to your existing PHP Scripts!

3) phar – PHp ARchive

This is a cool new feature.  Think of it like an archive, like a .zip file or a .tar file. Besides just being able to group all the files into one simple file, we will be able to deliver and run an entire PHP application from a single file!

We will also be able to use phar archives within PHP, so the following will work in PHP 5.3 and above

<?php
include "singlefilelibrary.phar"
?>

Obviously, there will be a performance hit but the possibilities are endless, imagine being able to upload phpMyAdmin to the server as a single phar file instead of hundreds of small files.

4) Closures & Lambdas
This gets into the list because this is something most web developers would have been familiar with while working on Javascript. A lambda can be declared anywhere and they can be assigned to a variable. A closure on the other hand are lambda funcions but have access to the variables where they were declared. This is something called lexical scoping. To see this in action take a look at this example.

<?php
$hellolambda = function () {
echo "Hello world via Lambda";

}
$hellolambda(); // Outputs Hello world via Lambda
?>

5) All of the rest!
There are a lot of other things in PHP 5.3 which I thought are nice, I have just described all of them very succinctly.
Functors: This allows an object to be invoked as a function.
Traits: This is a new unit of reuse, traits can be incomplete, provides reusability, modularity and structure. In short it is copy-paste glorified!
Magic functions: We have a couple of new magic functions for classes (interceptors) __callstatic() and invoke()
Ternary operator: You can now display the a value that exists $value1 or $value2 using this simple statement echo $value1?:$value2;
There are many more things added like Late Static Binding, Variable Static Calls, Changes to PHP Error Levels, new PHP functions, improvements to help with OpenID, Command line and many more.

Final Thought
Well, this gives us much more to play with. It is definitely a lot to include into PHP 5.3 and I would have expected so many changes to go into PHP 6. I sometimes wonder if there will be anything new left to add into PHP 6 given the fact that so much has been released already.  If you are interested in PHP 5.3, do give it a try here, it is in beta at the time of the writing.

Also read...

Comments

  1. Janet Alison said on :

    Yup this is great!

    Namespace Aliases finally in PHP :)

  2. AnonCoward said on :

    I really dislike the binding with MySQL. There are other databases in some way better than mysql. That native driver will drive a lot of new project to tie on a specific DB.

  3. JC said on :

    PHP uses the backslash to dereference namespaces.

    So it’s: Blog\save(); and Comment\save()

  4. Bob said on :

    AnonCoward: the smart programmers use a database abstraction layer anyway

  5. Matías said on :

    Lambdas!
    Sweet

  6. Tero Simon said on :

    Does any one know of any windows specific improvements?

  7. Puneet said on :

    m very new to php … can say a newbie in php trying to learn coding :D

  8. masklinn said on :

    But wait, it gets better (now I got that from reading the docs, I’m not going to run pre-release versions of PHP when I’m not running the stables).
    As you may know, there are two takes on closures in imperative languages: Python’s “incomplete” closure where you get a read-only access to the lexical context (nb: something’s been kludged together for Python 3 but I don’t like, although it has the advantage of a consistent behavior) and everybody else’s where you also get write access (to the references that is, the objects themselves are r/w in python if they’re modifiable).
    Which one do you think the PHP devs picked?
    If you said “all of the above”, you’re right as far as my reading of the closure “design” document goes: PHP’s anonymous functions are of the basic (and fairly sane) form
    $var = function ($arg1, $arg2, …) {
    // body
    }
    you create a closure by adding a use statement to specify the parts of the context you want to bind
    $var = function ($arg1, $arg2, …) use ($c1, $c2, …) {
    // body
    }
    but that one passes the context variables by copy (same as the functions), meaning you get python-style incomplete closure. If you want to get “full” closure you have to add PHP’s good old “pass by reference” prefix:
    $var = function ($arg1, $arg2, …) use (&$c1, &$c2, …) {
    // body where $c1=whatever will rebind it in the outer scope
    }
    You can guess that I don’t find that “solution” much more impressive than Python’s…

  9. OvidPerl said on :

    For PHP amateurs? Isn’t that redundant? :)
    (Note the smiley. That means I’m kidding. Back off or I’ll kid again. I kid you not. Or something like that.)

  10. aaron_davis said on :

    @OvidPerl Everyone back off! This guy has a smirk, and he knows how to use it!

  11. cezar said on :

    PHP could be great if the dev team would grown the balls to make a backwards incompatable relase.
    Drop the . for concatination and make it for objects and methods, use + like everyone else. Stupid -> is annoying and ugly.
    Good job on namespaces, but Python is still beating with from something import thing.
    Clean up the standard function set and standard library. Decide if it is function(needle, haystack) or function(haystack, needle).
    Problem with PHP is that it’s a giant ball of things grown organically, but no one has had the courage to clean it up.

  12. MazonM said on :

    @cezar
    If that happened, PHP would lose the biggest advantage it has over languages like Python: a huge amount of 3rd-party software. There’d be few reasons left to use PHP for a new project, and existing code could be rewritten in Python about as easily as it could be converted to the new backwards-incompatible version (depending on exactly how much changed). Only the people with a big investment in PHP would stay with it, thus turning it into the new COBOL.

  13. Buzzard said on :

    @cezar
    Drop the . for concatination and make it for objects and methods, use + like everyone else
    That’s one of the few things PHP did correct, it removes any ambiguity between addition and string concatenation.
    Stupid -> is annoying and ugly.
    I personally don’t find -> annoying or ugly (especially if it lets me have the concatenation operator)

  14. MazonM said on :

    PHP’s weak type system makes having separate operators for addition and concatenation necessary. Strings and integers are regularly used interchangeably in PHP, and all the math/string functions accept both (AFAIK).
    $ php -r ‘$a = “string”; var_dump(max($a, -4));’
    string(6) “string”
    $ php -r ‘$a = 0xDEADBEEF; var_dump(substr($a, 4));’
    string(6) “928559″

  15. hobbit125 said on :

    Oh sure. I think we can call Ruby and Python mainstream at this point. There are several books at your local B&N on the languages, and some pretty big companies using them (python particularly.) There are also more and more job postings for them coming which is good news if you’re a Ruby or Python guy.
    In fairness, VB.NET got closures and lambdas in it’s last version (9.) Here’s what it looks like using a lambda that encloses:
    Dim y as Integer = 5

    ‘…

    List.Filter(Function(x) x < y)
    One thing that really sucks with VB’s lambdas though: they can only be one line of code. Pretty lame, but it does cover more cases than one would at first imagine. This is fixed in VB10 AFAIK.

  16. mernen said on :

    His description is very poorly worded, but I’m guessing it’s basically the ||/or operator of languages like JavaScript, Ruby, Lua and Python. In these languages, the logical operators return the values that passed/failed the test unmodified, while PHP’s || always returns either 1 or 0, so it can’t be used the same way.
    If I’m right, foo ?: bar would be roughly the same as foo ? foo : bar then (except it would evaluate only once, so it’d still be efficient with function calls, for example). A (somewhat) practical, overly simplified example:
    $page = $_GET["page"] ?: 1;
    $language = $_COOKIE["language"] ?: “en”;

  17. troelskn said on :

    The syntax is ugly, but at least it works. The main reason for this design is to preserve backwards compatibility. Since the rest of PHP uses dynamically scoped variables, there is no clear way to add static scope while preserving behaviour.

  18. masklinn said on :

    @troelskn
    Uh no. PHP basically has no scoping (variables are either global or function-scoped). It’s definitely not dynamic scoping which would be much weirder.

  19. troelskn said on :

    @masklinn
    Seems I got the concepts mixed up there. And I’m not even correct about “preserving behaviour” either.
    The point I tried to make was that it would change the semantics of the language to add lexical scoping, and it could cause some confusion for those people using php as a procedural language. At least, that was the reasoning, as I remember it.

  20. masklinn said on :

    @troelskn
    Of course it would, but the question is… would it break it? In Python it didn’t, I expect that the only thing that would “break” is when you use nested functions in PHP (which is currently stupid since it simply creates the nested function(s) at toplevel). Not exactly an important breakage, and one that could be warned against during some kind of “ramp up”. As for confusion, which one? People using PHP as a purely procedural language aren’t going to nest functions, and if you don’t nest functions you won’t see the effect of lexical scoping.
    Finally, as far as I know it didn’t break Python.
    I expect that they won’t add lexical scoping ever though, not because they don’t want to but because they’re not able to, whether or not they want it.

  21. troelskn said on :

    @masklinn
    Even if the average Joe doesn’t intend to use lexical scoping, he will still run in to it, from time to other. So it does add complexity. The language is already quite complex (some would say bloated), because there has been little control in the past, with what went in and what didn’t.

  22. sunlight_smiles said on :

    I want a discussion about the implementation of both.
    Why are they using \ instead of :: for namespaces? Is it really because the parser wasn’t up to scratch? Or is it because of confusion with the static members of an object?
    Why do I have to declare which variables enter the lambda? Why can’t the so called closure simply inherit the total lexical scope like it does in every other language? If this is a hack for performance, say so, and explain why… don’t hand wave it away.
    As for phar archives… its mentioned there will be a performance hit. But will APC and other opcode caches be able to save the internals of phar archives?
    Etc.
    This article just bullet lists the new features. Sure now I know they’re in, but that’s it. Too many PHP articles feel like they have the depth of a ‘cheat sheet’ for me, so I decided to complain today and see if anyone else shared my concerns.

  23. TruthPicker said on :

    Yay! More cool shiznit!

  24. NashMcCabe said on :

    Not a php expert by any measure, but what’s wrong with . as a separator?

  25. the_classifier said on :

    that’s the string concatenation operator.

  26. sjs said on :

    @NashMcCabe
    Yes . is catenation in PHP but that alone doesn’t preclude it from also being a lookup operation (imo).
    PHP allows a form of metaprogramming by simple string variable substitution. If you imagine the example given here but with an instance instead of a class function then you can see how the . in that context is ambiguous.
    $ns = “Namespace”;
    $fn = “functionName”;
    $ns.$fn(“hello”); // <<~ is this a lookup or a call to a function named NamespacefunctionName()?

  27. Matthew Turland said on :

    Note that Traits are still listed in the “Active” section versus the “Implemented” section of the wiki’s RFC page: wiki.php.net/rfc. So this is likely in PHP 5.4 maybe??.

  28. momo said on :

    I’m slow :)

    I don’t really see the advantage of namespaces yet… The example given looks like the same amount code with either comment_save or Comment/save. I get that you could group multiple functions funder a single class, but it just seems to be a matter of style preference more then anything else.

  29. texec said on :

    @MazonM: That’s not correct. (int) “string” == 1, so

    var_dump ( max ( ‘string’, 4 ) ); // prints 4

    @momo: You can separate frameworks and functions and use them in multiple contexts without renaming them.

    @sjs $fn(”hello”); works but $ns doesn’t work.

    @mernen Yes you are right.

  30. RaiulBaztepo said on :

    Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I’v just started to learn this language ;)
    See you!
    Your, Raiul Baztepo

  31. Trouts said on :

    Nice review.
    I believe PHP 5.3 is really great, i just hope they don’t get to embed Zend everywhere on it… Zend is a framework, It SHOULD be optional.

    On the syntax, the thing that is still missing is $arr = ['key'=>$val, 'key2'=>$val2, ...], short syntax for $arr = array(‘key’=>$val, ‘key2′=>$val2, …);
    With optional array arguments now everywhere in frameworks and libraries, this is a must have :/
    We really miss this on some naturephp plugins.

  32. Fujjedeilyav said on :

    Thanks for the post!!

  33. alex said on :

    can’t wait for anonymous functions :)

  34. Anonymous said on :

    good share, great article, very usefull for us..thank you

  35. Pingback: What is new in PHP 5.3 for PHP amateurs? | Web Developers articles, tutorials, help

  36. Damien said on :

    Hey there! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very
    good gains. If you know of any please share. Thank you!

Comments are closed.