Hacker News new | past | comments | ask | show | jobs | submit login
PHP 5.4.0 released (php.net)
258 points by 0x0 on March 1, 2012 | hide | past | favorite | 97 comments



Big hitters:

array dereferencing - $object->method()[$index] is now valid syntax

built-in webserver via CLI - php -s - http://php.net/manual/en/features.commandline.webserver.php

traits and the insteadof operator - http://php.net/language.oop5.traits.php

shortened array syntax - $array = [1, 2, [1, 2, 3], 4];

Finally removed register_globals ;)

Default charset of UTF-8!

Read all about it! http://www.php.net/manual/en/migration54.php


Also it is faster and much better on memory consumption (depends on app of course, but 10-20% speedup and 20-30% less peak memory have been observed on some mainstream apps).


Are these numbers based on most previous versions of PHP? I'm on 5.3.10, do you think if I upgraded I would see similar improvements?


Yes, most probably you will see significant improvements. Of course, it depends on your app - if your app spends 99% of time in SQL database calls, PHP can do nothing about it. But PHP part would be faster and take less memory.


In a word: Yes. Of course, depending on your app YMMV!


> Finally removed register_globals ;)

They've also removed magic_quotes. A few functions that queried its status still exist, but you can't turn it on.


That array syntax is beautiful, been waiting for that for a long time.


This bug was apparently “not a bug”: https://bugs.php.net/bug.php?id=51672


Well, it wasn't a bug. That was more of a feature request which is now implemented.


It’s been a feature request for at least eight years, it should never have arisen in the first place, and it should have been a one-line fix even if it had arisen. I don’t mean to knock PHP too badly; it’s quite useful, even if it is rather quirky. I just find it so unfortunate that this silly thing got so out of hand.


It's not "one liner", and couldn't be if you understand how PHP engine works. But it wasn't super-hard to implement, just nobody got to it till now.

It did not "get out of hand" by any measure. Once there was a consensus that this feature is needed by the significant part of PHP community, it was implemented. Could it be done earlier? Maybe, so could a lot of other nice things.


You forgot (new Object)->method()


The www.php.net mirror will only be rsynced tomorrow, for now use http://docs.php.net/manual/en/migration54.php instead to get infos about 5.4 features. It's a good bit more up to date.


Really looking forward to traits. We have some hacks using interfaces and __call that we have been using to try and approximate traits, but the real thing is always much better. :)


Same here. This is a move away from inheritance to mixins. They did a stellar job with it and it's really flexible. Check out http://us2.php.net/traits for the nitty-gritty.


I've used traits a few times and in each case replaced it later by either inheritance or moving the functionality into separate classes. I'm not getting the design considerations that call for traits over alternatives. How would one use, and why is it the better option?


Amongst other things, traits are a way to provide interface delegation. Imperfect, but a lot better than the current solutions.


I am curious what the internal hang up is which prevents:

funcReturnsFunc(1)(2)


> I am curious what the internal hang up is which prevents:

PHP's parser is... not exactly a great work of software engineering.


> PHP is... not exactly a great work of software engineering.

FTFY. :)


You can do better? As smart man as you are surely can figure out where to send the patches.


Main problem there is $foo→bar()() which seems to be harder to implement on top of existing parser. Otherwise the patch is here: https://wiki.php.net/rfc/fcallfcall but since it's not complete it wasn't merged.


Some of those might just make me do some PHP again.


My thoughts exactly. If the situation warrants it.


I just did a Google search for register_globals... mind boggling.


PHP was originally designed for simple, procedural bits of logic inside individual HTML pages. In that context, there's nothing wrong with the feature itself.


This is a nice list of improvements. As someone who spends a lot of the day in PHP-land, this is going to make me happy. As someone who also controls our entire server stack, waiting for someone else to decide to upgrade will not be a problem :)

I'm glad the PHP devs are starting to actually make it a "real" language. It seems like PHP has always been the fat kid bumbling along behind everyone shouting "wait up guys!!" With closures in 5.3, syntax improvements and removal of horrible features (register_globals, magic_quotes, etc) in 5.4, it's shaping up quite nicely.

Thanks, PHP devs!


> waiting for someone else to decide to upgrade will not be a problem :)

It is sad that a lot of servers are not like this, and PHP 5.4 will take ages to appear, if at all.

Heck, I know of a hosting company still using PHP4.


Funny, I just had to deploy an existing site to a PHP4-only hosting environment. After a few hours of re-writing things I've been taking for granted (a lot of timezone code namely) everything worked fine. But yuck, I felt dirty afterwards.


Hosting company that still uses PHP4? Name names so we can avoid and chastise them!


Media Temple for one. For a domain or subdomain you had to explicitly choose PHP5 instead of the default PHP4.


They actually changed this recently. The default is now PHP5, with an option to select PHP4.


It's not really sad, some administrators don't like immediately upgrading to the latest and greatest version. Anyone running Debian stable will probably not get 5.4 until 2013.


I've booted up my home server after ~7 months of down time that has virtualized distros. It was funny to watch Debian 5 aptitude safe-upgrade ending in ~2 mins with less than 15 packages and Gentoo emerge -udNav world being busy nearly all night. That just displays two radically different philosophies and I have nothing against either, though I prefer to be up to date and flexible.


They also improved the zend engine, CURL extension, added Tokyo cabinet abstract and Berkeley DB Support! Added a couple of hashes, Improved JSON Extension (JSON_NUMERIC_CHECK!) and a whole lot of bug fixes. The UTF-8 part was long overdue, glad they fixed that.

I spend a lot of time programming in PHP. Its reputation is pretty bad, but updates like this keep me going!


PHP was my first love (actually my second, after QBasic) when I was a teenager.

Would love to get back into it now that it's a "real" language.

Got any good tips about books on modern PHP programming?


Books... not so much. I have another idea: you could check out an MVC-framework like codeigniter or CakePHP. There are numerous tutorials about them, and they give you the added benefit of working with an MVC pattern (knowledge you can use in other languages and frameworks as well, such as Ruby on Rails) and working Object Oriented.

In my opinion, a big drawback of PHP is that it's so easy to screw up because it's easy to pick up. There are so many tutorials out there which will let you make a procedural, cross-scripted, sql-injected security liability spaghetti code... Starting with CodeIgniter or CakePHP is not very hard, especially when you have a little understanding on basic programming with PHP. Good luck!


CodeIgniter and CakePHP are great examples of code badly brought forward into PHP5 from PHP4 roots. I wouldn't recommend either to either a novice or an expert; CodeIgniter is a fantastic example of out-of-date practices and CakePHP an example of writing such abjectly slow code that everybody else benchmarks against you to look good.

If you're going to use PHP5, Symfony2 is a well-reasoned, best-of-breed system.


I'd also recommend Kohana. It was originally a fork of CodeIgniter, but version 3.0 was a complete rewrite for PHP5. Compared to Symfony, it's more of a barebones framework.


I wouldn't. Kohana's track record of cavalier response to security concerns is off-putting and their code is not particularly impressive.

There's a reason people who use PHP are getting on @fabpot's train and not Kohana's, and that's because Symfony2 does much, much more right than anyone else in the conversation.


Since you're not a beginner programmer, I recommend PHP Objects, Patterns and Practice

http://www.amazon.com/Objects-Patterns-Practice-Experts-Sour...


Other great little changes:

  - you can now do function()[0] 
  - <?= always on despite what you say in the INI
  - safe_mode always off
Seems like a return to sanity for the PHP team, at least temporarily.. I even kinda like the traits!


How is '<?=' being always on great change? I always thought it was weird and kind of stupid, but I'm genuinely curious how is that great thing.

Also,

  Chained string offsets - e.g. $a[0][0] where $a is a string - now work.
I have no idea how is that supposed to work. What should be the outcome on, say:

  $a = "foo"; $a[0][0]
What about (assuming $a is still "foo"):

  $a[0][1]
etc.?


Many people write their PHP views in raw PHP to remove the (albeit small) overhead from a templating system. I think this is where the PHP short open tag syntax gets used the most (I know I use it there a lot), this is because:

<?=$username;?>

(Personal Preference Alert!) Is easier to read, faster to type and easier for designers to handle than:

<?php echo $username;?>

The downside is, if you deploy your code on a server you don't have access to (meaning you can't enable short tags via php.ini) then you'd have to painfully replace every "<?=" with "<?php echo" BY HAND, find and replace is not allowed.

Eventually, there was a big argument over whether short open tag should be removed in PHP6 (it's not), the biggest reasons for removing it (from what I remember) was that it could conflict with the "<?xml" tag and if you don't have access to php.ini or a modern code editor, you're screwed.

The removal of one of these major problems (by forcing short open tag to work regardless of php.ini settings) brings PHP's short open tag one step closer to being loved and admired by everyone, including YOU, so get used to thinking things like this are great.

As far as chained string offsets, who cares! Long live short open tag! (Sorry I couldn't help it.)


> How is '<?=' being always on great change? I always thought it was weird and kind of stupid, but I'm genuinely curious how is that great thing.

When you share your code with various clients (open source, software seller, ...), you can not assume that short array are on, thus you have to use <?php echo $var ?> everytime instead of the shorter <?=$var?>. Having the second syntax always working solves that, this is on the same level as the short array syntax change, removing a hurdle and letting you concentrate on more important stuff.

> $a = "foo"; $a[0][0]

$a is a string "foo" $a[0] is a string "f" equating to substr($a, 0, 1) $a[0][0] is a string "f" equating to substr($a[0], 0, 1)

> $a[0][1]

This will give an undefined index error, same thing as $a[42] for exemple, since index 1 doesn't exists in $a[0] (= "f")


> thus you have to use <?php echo $var ?> everytime instead of the shorter <?=$var?>

Is this really a huge concern? I guess I just have $tockholm syndrome at this point, and am used to writing <?php echo $var; ?> explicitly every time, precisely for the reasons you mentioned. It's one less thing to worry about.


I'd say that "<?=" being always-available is a verbosity reduction along the lines of short array syntax. The alternative of using "<?php echo" can be quite noisy for some (me).

This allows short tags to be disabled for XML clash-avoidance while still allowing the user to use the short-form of echo.


I always thought it was weird and kind of stupid, but I'm genuinely curious how is that great thing.

How is it weird and stupid? <?php echo $var ?> is better than <?= $var ?> ?


Good tools complain about <?= because it does not start with a named target. A lot of people just haven't read about the idea behind processing instruction syntax, which is also why we keep seeing mistakes like <%.


A PHP script isn't an XML document, so processing instructions aren't really relevant. Even if your script is outputting XML, the script itself isn't going to be read by an XML parser.


It can if you want. It's not that hard to make documents which are valid before and after scripts run. This enables many more tools to work with them.


for '<?=', I see it as a good thing for using php for views. It's faster and more natural to read within typical display markups. Akin to the erb syntax.


> $a = "foo"; $a[0][0]

It makes sense when you think of it in offsets. $string[offset] means that given $a = 'foo' then $a[0] is f and given $a = 'f' then $a[0] is f. Thus $a[0][0] would be the first offset of the first offset of "foo". $a[0][1] would not be valid, of course.

Also it's not really something you should ever use, but it's definitely more consistent than throwing an error.


sorry when you are motoring through code typing <?php echo $var vs <?=$var it gets to be tedious.

I understand for general php portability that its better to use the <?php echo vs <?=$whatever syntax, but less code is a good thing.


They finally added short array syntax, removed register_globals and magic quotes, and the default character set is now UTF-8!

This is good news indeed, they seem to be actually improving the language for once.


Seems like the multiyear unit-test coverage campaign is starting to pay off for the core PHP engineers, 5-6 years ago they swore they couldn't do shortened array syntax without major problems.


Also awesome:

"Arrays cast from SimpleXMLElement now always contain all nodes instead of just the first matching node. All SimpleXMLElement children are now always printed when using var_dump(), var_export() and print_r()."


I'm glad to see the short array syntax. Having strayed from PHP for a while to work on Ruby and JavaScript I'm really enjoying the ability to leave out semicolons in unambiguous end-of-line situations. Would love to see that make it into PHP at some point.


The best part of short array syntax is that now you don't need named parameters to be supported by the language.

    function foo($opts) {
      echo $opts['source'] . $opts['destination'];
    }
    
    // just one extra pair of [] needed instead of new array()
    foo(['source' => '/123', 'destination' => '/abc']);


Unfortuately, this method of passing an array as a single parameter, rather than actual parameters, is not very self-documenting and leads to more difficult to understand code.


> The best part of short array syntax is that now you don't need named parameters to be supported by the language

Unless you've ever used languages with actual first-class keyword arguments (Python) and languages using hashes as pseudo-kwargs (Ruby, JavaScript). Then you know it's no substitute.

Also, you could already do just that in PHP before, it simply took 5 more characters.


While I agree that it makes it easier to hack in that functionality, it would still be very useful to have named parameters for functions that don't implement that functionality.

For example, fgetcsv takes parameters for delimiter, enclosure, and escape char (as of 5.3). Right now, if I want to specify a different enclosure, I'm forced to specify a delimiter even if I still want to use the default. I'd much prefer the ability to tell the function call that I want to override the enclosure and leave the delimiter alone.


> While I agree that it makes it easier to hack in that functionality, it would still be very useful to have named parameters for functions that don't implement that functionality.

Absolutely. But PHP devs have repeatedly refused to support named parameters so this is a good enough fix.


> this is a good enough fix.

The story of PHP's life.


You could do that before short syntax:

    foo(array('source' => '/123', 'destination' => '/abc'));
Short syntax will make it less repetitive though. You can also use something like array_merge to emulate jQuery's $.extend for creating defaults.


It took them long enough! In 2008 They voted 14/9 against short array syntax, even though a key user group voted 17/3 pro...


Isn't that a bit like leaving a loaded handgun laying around? It's unambiguous today, but what if someone else starts working with your code and it's no longer unambiguous?

(edit: talking about JS only.)


From here: http://www.php.net/manual/en/migration54.other.php

> Chained string offsets - e.g. $a[0][0] where $a is a string - now work.

Can someone explain why this is? I'm sure I'm misunderstanding, but this seems to mean that the following would work:

  $a = "Hello";
  echo $a[0]; //"h"
  echo $a[0][0]; // also "h"??
What's the point? To avoid failure if I pass a string instead of a 2-dimensional array?


Consistency. Since $a[0] is a string, you would expect $a[0][0] to work too.


Thanks. Let me rework my original question then. Why the hell didn't it always work?

  php > $a = "Hello";
  php > echo $a[0];
  H
  php > echo $a[0][0];
  PHP Fatal error:  Cannot use string offset as an array in php shell code on line 1


PHP always seemed to have something weird in the parser about subscripts/array indexes. It's been there since I started using it during PHP3. Another similar fix they performed is making func()[0] work - before you had to do $tmp = func(); $tmp[0]. An old, old bug finally fixed.


Closures can now have a `$this` (by default it is the class in which the closure is declared). No more $that = $this hacks :)


There's also Closure::bindTo() [0], which should allow you do do slightly more functional programming, like JavaScript's Function.apply() [1]

[0] http://docs.php.net/manual/en/closure.bindto.php

[1] https://developer.mozilla.org/en/JavaScript/Reference/Global...


These features can only be good for PHP. Now the community needs to step up and care for the language better. We have seen the popularity of many languages and frameworks rise and fall, but php keeps chugging along. Modern frameworks are awesome, but the community is still rather fractured. I would love to see people more proud of php, to get over the fads around them. Now the language is getting some nice features, I think it's our time to shine :)




the ticket says Closed, so it better do.


One thing that's pretty important too is PHP-FPM. I've been dreaming about this for a long time for my nginx deployments.

http://php-fpm.org/


Hasn't PHP-FPM been part of the PHP core for a while now? Since 5.3.3 (mid 2010) according the PHP FPM site.


Yes but has of 5.4 it is now considered stable, whereas before it was still experimental (even tho it worked fine).


They shipped it with 82 failing tests.

http://gcov.php.net/viewer.php?version=PHP_5_4

Why even bother having a test suite?


I'm not sure what's more worrying:

* 82 failing tests

* 44 expected test failures

* 1119 compiler warnings

I want to believe that PHP is growing up, but I have to admit I'm not convinced.


When will this be available for FreeBSD? I really can't wait for traits, short array syntax and "foo()[0]". This is really a nice upgrade. Good job PHP team!


Are there any benchmarks (synthetic or real-world) for the performance improvements? Would have been nice if the release notes had provided some.


There are some around like http://news.php.net/php.internals/57760, seen a couple more but forget where. The trend does seem to be towards far better performance across the board though which is good.


I see a lot of mentions of zend in extension names, function names.. Could someone elaborate how Zend relates to PHP?


Zend Technologies Ltd. is a company started by Zeev Suraski and Andi Gutmans. The product of theirs you most likely heard of is Zend Framework, a PHP framework. It's however not their only product. Another one is the Zend Engine, which is a PHP interpeter and the virtual machine at the heart of PHP and the reason there are references to Zend all over the place.


Zend developed the Zend Engine, a virtual machine. PHP4 is based on the Zend engine. Zend is more than just the framework, it literally is the core of PHP.


array dereferencing - $object->method()[$index] is now valid syntax

finally ....


shortened array syntax - $array = [1, 2, [1, 2, 3], 4]; ..... can't express how long i waited for these


Added callable typehint.

Nice


Oh that's a nice one I hadn't noticed yet. Now all that's left is type hints for scalars...


Now the question is, when will this become available in mainstream Linux distributions? I guess Arch et al. will get it pretty quickly, followed by Ubuntu 12.10 or maybe 13.04 depending on how many packages it affects.

Good ol' Debian, on the other hand, might or might not get it in time for the Wheezy freeze. CentOS? Forgetaboutit.


You mention two distros that are designed for stability. Thats very different from following the bleeding edge and they have their purpose and reason for it(Which while developers like myself and I assume you sometimes forget, our server admin friends never do). If you want to follow the leading edge there is always also the option of making your own packages.


I use CentOS in my stack. It's going to get it today. Because I'm going to compile it =)


You may want to try DotDeb [1], they already have PHP 5.4 packaged for Debian :-)

[1]: http://www.dotdeb.org/


There's nothing stopping you from using, say, remi or webtatic repos on CentOS.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: