New Features in PHP 5.6

It’s no blasphemy saying the core devs of PHP have had some hiccups and some truly ridiculous arguments about some of the features – just look at this silly discussion on why a shorthand array syntax is bad, back from ten years ago. Arguments like these, among other things, make people think some of the core devs don’t even use PHP in their day to day lives, and are why the devs of PHP and the people using PHP are often considered unprofessional.

The future isn’t bleak, though. It’s been a while since the release of PHP 5.4, and new versions have been coming out faster and faster ever since. When 5.5 hit and introduced some unexpectedly great features, the PHP community breathed a sigh of relief and regained hope of a more dedicated, structured and smart core development. Whether or not we’ll actually get this remains to be seen, but the future does indeed look promising, especially if one looks at the PHP 5.6 changes made so far.

While a full explanation of all the upcoming updates would be far too vast to cover in one article, I would like to direct your attention at some I personally deem most important.

MIME types in the CLI web server

MIME types in PHP can be used to output content as a type other than PHP, that is, as a type other than text/html. When you run a PHP page, the default output is text/html, but you can use headers to set it as, for example, PDF and generate PDF files. When a server is aware of different MIME types, as most servers like HHVM, Apache and Nginx usually are, they know how to serve a given file by default, judging by its extension, without you having to set specific instructions in PHP itself. The command line server from PHP 5.4 had only a few MIME types so far, and this version will introduce dozens more. It’s safe to say that all the common MIME types will be covered by the built in PHP server now.

Internal Operator Overloading

This is a feature we as web developers using PHP probably won’t be exposed to, due to the keyword “internal”. Internal means “non userland” where userland is the area of PHP development we, the end users of PHP, use. It applies only to internal classes, in order to make development in that area simpler and code cleaner to read. A detailed explanation can be found here.

Uploads of over 2GB are now accepted

Until 5.6, no uploads of 2GB and over were supported in PHP. This is no longer the case, as the changelog states, and uploads of arbitrary size are now supported.

POST data memory usage decreased

POST data memory usage has been shrunk by 2 to 3 times, following two removals: the always_populate_raw_post_data setting from php.ini, and the superglobal variable $HTTP_RAW_POST_DATA. What this means is you can no longer access raw post data that way, but need to rely on a solution such as:

$postdata = file_get_contents("php://input");

Note that getting POST via ://input is unavailable when a form is multipart (in other words, when a form has a file upload element).

Improved syntax for variadic functions

Variadic functions are functions which can take an arbitrary amount of arguments. When you supplied some arguments to it, you usually had to do some splicing after calling func_get_args, which was somewhat impractical. As taken from example here, the syntax in 5.5 and earlier was:

class MySQL implements DB {
    protected $pdo;
    public function query($query) {
        $stmt = $this->pdo->prepare($query);
        $stmt->execute(array_slice(func_get_args(), 1));
        return $stmt;
    }
    // ...
}

$userData = $db->query('SELECT * FROM users WHERE id = ?', $userID)->fetch();

now, the syntax will be:

class MySQL implements DB {
    public function query($query, ...$params) {
        $stmt = $this->pdo->prepare($query);
        $stmt->execute($params);
        return $stmt;
    }
    // ...
}

As you can see, the ...$params syntax tells the function to accept the first parameter as is, and to put all the others into the $params array. This rids us of the splicing and calling func_get_params, improves function signatures, and makes the code more readable.

The new syntax also allows passing of extra arguments by reference, by prefixing ...$params with an ampersand, like so: &...$params. This was not possible before with func_get_args.

Argument unpacking

Note: thanks to nikic for pointing out this feature – it got implemented around the time of this article’s original writing

Following improved support for variadic functions, argument unpacking got approved, too.

Until now, the only way to call a function with an arbitrary number of arguments passed in as params was by using call_user_func_array meaning literally “call userland function with array of params”. This was clumsy and awkward, wasn’t supported in constructors, was slow, and required a callback in the form of a string – a function name – which means no IDE support in most cases.

Unpacking would eliminate all the downsides of said function, and naturally complements the variadic support seen above. Unpacking works like so:

$args = [1, 3, 5, 7, 9];
MyClass::someMethod(...$args);

This is the same as calling

MyClass::someMethod(1, 3, 5, 7, 9);

i.e. passing in the arguments in one by one. This works in any concievable scenario, from class constructors to being called multiple times in a call, anything goes. See the RFC linked above for usage examples and further explanations.

Constant Scalar Expressions

This RFC added the ability to have expressions in places that only expect static values. What this means is you can now have basic arithmetic and logical structures in constant declarations, functions arguments, class properties etc.

For example, previously, code like this would throw an error:

const a = 1;
const b = a?2:100;

Now, this is no longer the case.

One might argue whether a constant really is constant if it depends on the value of another constant, but such meta discussions are better left for other times.

PHPDBG bundled by default

The gdb-like debugger, phpdbg, is now bundled by default as SAPI. It’s used from the command line, or a simplistic Java UI, specifying break points interactively, altering programs at runtime and more. It can also inspect Opcode, and be used from withinyour PHP code. Learn more about phpdbg here.

Zip improved

The Zip library got several improvements, particularly in the form of new methods. One that stands out especially is ZipArchive::setPassword($password) which finally allows you to easily create password protected Zip files.

Importing namespaced functions

As per this RFC, the new version will allow importing of namespaced functions and constants. Right now we are able to import namespaces and types (classes/interfaces/traits) via the use statement, like so:

namespace foo\bar {
    function baz() {
        return 'foo.bar.baz';
    }
}

namespace {
    use foo\bar as b;
    var_dump(b\baz());
}

From 5.6, we’ll be able to use the use function and use const statements to import a lone function or constant (even class constant).

namespace {
    use function foo\bar as foo_bar;
    use const foo\BAZ as FOO_BAZ;
    var_dump(foo_bar());
    var_dump(FOO_BAZ);
}

Conclusion

PHP 5.6, which as of this moment still doesn’t have a release date, definitely looks promising, and hopefully this short overview of the changelog helped you understand how important it will be for you to upgrade as soon as it’s out, if at all. For the remainder of the upgrades, please see the NEWS file, and keep checking back for updates. If I’ve missed something important, or misinterpreted something, please let me know in the comments below.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://saharahacker.com/ Sam the Sahara Hacker

    Awesome on the variadic functions!

  • http://www.isights.org/ Michael Long

    Is that var_dump(b/baz()); or var_dump(bbaz()); ?

    Sigh. Just another case of PHP finding and using the worst possible set of symbols to represent any given operation.

    C#, Java, and Javascript use dot notation. C++ uses “::”. But no, PHP had to blow the concatenation op with “.”, which prohibited using dot notation for object method calls and name spaces. And they used “::” for object scope resolution.

    Guys, there’s a difference between being better, and being different just for the sake of being different…

  • Etienne

    The link to “this silly discussion” isn’t working, you forgot the http://

    • http://www.bitfalls.com/ Bruno Skvorc

      Thanks, fixed!

  • Акакий Акакиевич

    “Improved syntax for variadic functions” – Looks awful. Vague description of the reasons for innovations. For what?

    “Note that getting POST via ://input is unavailable when a form is multipart (in other words, when a form has a file upload element).” – Another bike. The logic of the language depends on external factors. No clear reason why you can not access to the not binary data from the multipart form.

    • Mikushi

      The syntax for variadic functions is pretty standard, very similar to C, ActionScript, Basic, C++, D, Go, and probably more that I am not aware of. It is a useful tool, to concatenate strings for example, hell, printf is a variadic function…

  • sebastiaan hilbers

    Looks like minor changes to me… I like the variadic arguments a lot, though I like the way coffeescript works with splats even more

  • http://www.matthewsetter.com/ Matthew Setter

    I’m liking the namespace changes. At this stage I don’t have a specific use for them, but could see it coming up quite quickly.

  • Kevin

    “Yeah”, it took a ton of discussion to stick with “” for namespaces :-)

    copied content:

    ============

    The most heavily discussed topic in PHP development history was the selection of the namespace delimiter.

    We came up with the backslash.

    <?php
    namespace Foo { class Bar { public static $Baz; } }

    FooBar::$Baz = 'wtf?';

  • Roy

    Thanks for the overview, it’s easily digestible compared to the dry changelog and some extrapolation on some of the key new features is always welcome.

    • http://www.bitfalls.com/ Bruno Skvorc

      Thanks for the feedback, glad you approve!

  • dojoVader

    I somehow find it hard to grasp varadic arguments , i guess tomorrow when the head is less plagued by headache. nice article

    • http://www.bitfalls.com/ Bruno Skvorc

      Thanks! It takes some getting used to, the syntax looks weird, but I can see the feature getting widespread adoption fast.

    • Mikushi

      It’s actually pretty straight forward, I did a lot of ActionScript 3 back in the days (hah!) and it has variadic functions. Basically …$params can almost be read literally as “and then $params”, where $params becomes an array containing whatever arguments might be passed to the function after the declared ones, one or a thousand extra, they’ll be in $param. And that’s it!

  • philsturgeon

    “Arguments like these, among other things, make people think the core devs don’t even use PHP in their day to day lives”

    Well that is offensive. “Some of the core devs…” maybe.

    “One might argue whether a constant really is constant if it depends on the value of another constant, but such meta discussions are better left for other times.”

    define(‘B’, a?2:100);

    It’s still a constant. Once defined, it is constant.

    • http://www.bitfalls.com/ Bruno Skvorc

      Changed to “some of the core devs”, cheers for the feedback!

  • http://www.bitfalls.com/ Bruno Skvorc

    No, just $HTTP_RAW_POST_DATA

    • dave harris

      When you say “No, just $HTTP_RAW_POST_DATA”, are you saying “No, it WILL still be populated” (disagreeing with littleguy’s question) or are you in fact saying “Yes, $_POST will not be populated anymore” (agreeing with littleguy). Please clarify.

      • Jooms

        $_POST will be populated. $HTTP_RAW_POST_DATA will not

        • http://www.bitfalls.com/ Bruno Skvorc

          ^ this