PHP 5.5.0 released!
PHP 5.5 has been released! Quite exciting stuff, and pretty great to see the pace of new releases. Props to the dev team!
Hopefully distros pick this version up quickly as well, so we can start making use of these fancy new features.
The highlights:
Generators
Generators provide an extremely easy way to create iterators. They introduce
a new yield
keyword, which kinda works like return
, but different:
<?php
function daysOfTheYear() {
$year = date('Y');
$current = new DateTimeImmutable($year . '-01-01');
do {
yield $current;
$current = $current->modify('+1 day');
} while ($current->format('Y') === $year);
}
foreach(daysOfTheYear() as $dt) {
// ...
}
?>
The benefit of this new syntax, is that you can now let these new generators act as if they returned an array, loop through them as usual, but the actual array doesn’t need to be in memory in advance.
Immutable DateTime object
In my previous example I used DateTimeImmutable
. In my job I deal a
lot with dates and times. DateTime
is therefore my tool of choice.
One mild annoyance, is that whenever DateTime objects are passed as arguments to any method, and you intend to do calculations based on them, you really want to make sure that you’re not modifying the original.
<?php
function printUTCTime(DateTime $dt) {
$dt->setTimeZone(new DateTimeZone('UTC'));
echo $dt->format(DateTime::ATOM);
}
// Created in a local timezone
$dt = new DateTime('now');
printUTCTime($dt);
// Now $dt is suddenly in UTC.
?>
Because my function name was called printUTCTime
, as a consumer of this
function it would go against my expectations that the object was also
modified. I’d expect it to just echo.
So, as a library developer I should first always clone any DateTime
I
get, before doing anything with them.
DateTimeImmutable
is a new object, similar to DateTime
. The difference is
that it’s, well, immutable. This means that after the object has been created,
it’s guarenteed to never change.
Methods like modify
, setTimeZone
and setTimeStamp
never alter the
object, but always return a modified copy.
Now, if we can also solve the following API usability feature, I’d be totally happy:
<?php
$dt = new DateTime('2013-06-20 16:00:00', new DateTimeZone('Europe/London'));
$dt->setTimeZone(new DateTimeZone('Europe/London'));
?>
The previous example is, as far as I know, the only way to create a DateTime
object in a specific timezone. The first timezone is needed to tell DateTime
what the reference timezone is, the latter to actually change it into that
timezone.
Anyway, as soon as my libraries require PHP 5.5, I’ll be changing all my
DateTime
objects to DateTimeImmutable
.
Lists in foreach
This adds some syntax sugar for some foreach loops. I quite like it:
<?php
$users = [
['Foo', 'Bar'],
['Baz', 'Qux'],
];
foreach ($users as list($firstName, $lastName)) {
echo "First name: $firstName, last name: $lastName. ";
}
?>
Example was directly taken from the wiki.
Finally keyword
Finally, the finally
keyword is also implemented into the language. (sorry,
had to do it).
finally
can be added to try..catch
block, and guarantees that regardless
of what happened within that block, finally
will always be executed.
<?php
try {
echo "1";
throw new Exception();
} catch (Exception $e) {
// Handle exception
echo "2";
} finally {
echo "3";
}
?>
The preceeding example will output 123
. The benefit of finally, is that it’s
contents will also be executed if the exception was not caught. If you need
any guaranteed cleanup, finally
is your tool.
Class name resolution
I write a lot of code that maps data structures to classes. An example of this can be seen in my vobject project.
As you can see there, that’s a huge list with a ton of repetition. The reason for this lies in the fact that when you specify a classname as a string, you cannot use namespace resolution.
Simpler example:
<?php
$class = 'Sabre\\VObject\\Property\\ICalendar\\CalAddress';
$obj = new $class();
?>
Well, starting from PHP 5.5, I can use a syntax like this instead:
<?php
use Sabre\VObject\Property\ICalendar;
$class = ICalendar\CalAddress::class;
$obj = new $class();
?>
Much cleaner, and prettier! Especially if you have a hundred of those in one file.
Opcode cache is now integrated and enabled by default in PHP
For years we had to manually install APC as a first step after installing PHP. It seemed silly that ‘being fast’ was not considered an essential language feature.
Now it is, and it wasn’t APC that made it into core, but rather an alternative from Zend.
Some more info can be found on the wiki.
Constant dereferencing
This is really just a fancy word for being able to do the following:
<?php
echo "Hello"[1]; // output 'e'
echo [1,2,3,4][3]; // output '4'
?>
Why is this cool? Not sure; I’m still trying to figure out when I’ll use this, but It’s great to see that the PHP engine is getting more consistent.
To conclude
Missing something?
Suggest edits or additions on GitHub
Comments
Thijs •
Thanks for the update on the new stuff
Shackrock •
Thanks for the GIF.
Hughie Wilmshurst •
Best thing about this post - zebra gif. That and the thing about using list() in a foreach loop, that could be handy.
Markus Staab •
great summary... but even better GIF
Phil Grayson •
One thing I'm particularly happy about, although I doubt I'll see 5.5 in my office any time soon, is empty() supporting arbitrary expressions;
empty(trim($name)) // Will now not fall over!
Guest •
I've been out of PHP for a while. Does constant dereferencing mean we can finally do things like this?
$bar = explode('_', $foo)[5];
Evert •
As fas as I know that already works perfectly from PHP 5.4 onward.
Guest •
Ah, you're quite right. Function array dereferencing... http://www.php.net/manual/e...
Nice one, thanks for the heads-up!
Pawel Decowski •
By “Constant dereferencing” you mean “Literal dereferencing”.
Evert •
I just copied the description from the wiki. Literal does sound better though :)
mindpower •
15 months since 5.4 and this is all we get in the way of improvements? Man, I'm glad I mostly work with Ruby now, PHP is really going nowhere!
me •
flame on... ruby really? lol
iansltx •
If you're going to troll, replace "we" with "you". I for one welcome our new php 5.5 overlords.
Also, just to clarify, are we talking straight-up Ruby, Ruby on Rails, or Ruby on some other framework? Because one ain't the other. And Zend isn't going to introduce huge BC/FC breaking changes (which would strand tons of the community on an old version) just to add sanity to argument ordering, no matter how much we'd like sanity in argument ordering.
brel moi •
2 things come to mind:
1-You're such an ungrateful person. Evert has busted his hump to do this and FOR FREE and this is how you thank him!
2-If you have nothing but negative crap to spew, you're either jealous or lonely...I'm guessing both. Do you happen to be American by any chance?
Cheers
Marcelo Silva •
Amazing GIF! HAHA!
lingtalfi •
Why are people so obsessed with that gif?
Thanks for the recap. I learned a couple of things there.
Cool zebra by the way.
Jaunty •
Great