Short array syntax finally in PHP 5.4
svn.php.net
svn.php.net
array_push
array_pop
array_slice
array_shift
array_unshift
array_map
array_key_exists
It kind of feels like they missed the point, saving 5 characters when you declare the array once, ignoring all of the other operations you do afterwards.
And this RFC, simple as it is, took 3.5 years to come to fruition.
The RFC (https://wiki.php.net/rfc/shortsyntaxforarrays) was actually rejected by the developers, I think it's only really been put in to appease large userland pressure. Find it rather amusing that a 2 change to the parser for an alias would be rejected on 'maintainability' grounds.
[1,2,3]->push(..) [3,5,6,]->pop(..) [7,8,9]->map(..)
etc..
The older functions could still exist for backwards compatibility, but people who want to write clean OO code could use the new style. $anArray->map(function(){}), $aString->pos('cow'), etc.
This would be a big step for PHP, and bringing the language closer to parity with Ruby and Python. Not sure how it works with eager type coercion, but JavaScript does it somehow.
What do ECMAScript interpreters do in such a situation?
In the example you gave, this is dependent upon operator precedence. Presumably any method calls are resolved prior to type coercion. This is how PHP and most languages work anyhow, correct? If you do `$this->do_something() + 20`, the method's return value is used. It doesn't try to turn $this into an integer and then call a method upon it. Same for `bcadd($anObj->meth(),34)`. So... I think that isn't a problem.
Because almost all the modern PHP frameworks use arrays to pass data, the short-array syntax makes viewing multi-dimensional arrays much easier, and thus will hopefully result in less bugs.
Example:
$this->link('My Link', array('names'=> array('a', 'b', 'c'), 'values'=> array('a1', 'a2', 'a3') ) );
becomes: $this->link('My Link', ['names'=> ['a', 'b', 'c'], 'values'=> ['a1', 'a2', 'a3'] ]);
Just removing the word array makes the code much easier to read, especially when you have deeply nested arrays.After having to use PHP for a while, it's no coincidence that these days I am using a whole new language.
For anyone who's curious, here's a list of the changes in 5.4 alpha 1: http://www.php.net/releases/NEWS_5_4_0_alpha1.txt
function boo(){
return array(1,2,3)
}
echo boo()[1];http://www.php.net/archive/2011.php#id2011-06-28-1
It's in PHP 5.4 alpha as well ;)
For example:
// explode splits the string on the provided boundary
// and returns an array containing each segment.
// using list() we can assign the two segments to two
// variables within the same statement
$size = "1000x1000";
list( $width, $height ) = explode( "x", $size );
Edit: Yes, it is a special form, but its still irregular, and that makes it shitty.
It's a language construct, not a function.
my ($foo, $bar) = f;
(foo, bar) = f()
var [foo, bar] = f(); list($foo, $bar) = f();
Given that PHP uses the array() keyword for constructing arrays, it is perfectly symmetrical. My IDE highlights the list() keyword just the same as all the other keywords.I also don't agree that PHP needs constructors to return $this for the same reason. You need to assign the object to a variable so you can reuse it.
$a = new Foo()->bar();
In this case if I later want to call another method on the Foo instance I have recreate it.My only wish is that they implement something that evaluates {} to (object)array(). It would come in handy when used with anonymous functions.
Anyway, I am pleased with the new syntax, but sadly, I have to use 5.2 as most of the time I'm working on WordPress projects...
$a = [1, 2, 3];
and it also will make function calls with named parameters much more readable.Sadly, it will be years before the majority of hosting providers adopt 5.4...
$a = [1 => [4, 5, 6], 2 => [7, 8, 9], 3 => [10, 11, 12]];
$a = array(1 => array(4, 5, 6), 2 => array(7, 8, 9), 3 => array(10, 11, 12)); [[4, 5, 6], [7, 8, 9], [10, 11, 12]]
work?I know PHP has a weird history of rebelling against its C-family-syntax heritage, but requiring the syntax in your example would seem specifically calculated just to make developers' lives harder.
[0 => [4, 5, 6], 1 => [7, 8, 9], 2 => [10, 11, 12]] [1 => [4, 5, 6], [7, 8, 9], [10, 11, 12]] $booking = $this->Booking->find('first', array('conditions' => array('Booking.booking_id' => $id), 'contain' => array('Review', 'Desk' => array('fields' =>
array('provider_id', 'category_id'), 'Provider' => array('city', 'name'), 'ProviderCategory' => array('fields' => array('provider_id', 'category_id'), 'DeskCategory' => 'name')))));
It's essentially not readable, but with [] it would work much better, and I still want to give keys to arrays.With VPS hosting as low as $6/month, what reason is there to continue using shared hosting anyways?
sigh Can the PHP devs focus on the real problems now? cough Unicode anyone? Ridiculously inconsistent naming of string and array functions? The woefully incomplete and useless STL? The lack of OO in arrays and strings?
Do you have actual real issues, or do you just like to complain about things you heard other people say?
Andrei Zmievski has been giving this presentation on what happened to Unicode in PHP. A huge amount of work went into making it happen but it eventually could not continue due to several reasons, including design decisions, lack of contributors & interest in the project.
An actual patch has been submitted for this before, and rejected by the PHP high muck-a-mucks, even though the community desperately wanted it, and the work was already done.
The fact that they finally gave in and included it means not only do we get a nice bit of sugar to sweeten up our programs, but also that maybe the community CAN steer the devs towards issues they care about.
Time will tell.
Why are you coughing about unicode? It works just fine as long as you use utf-8, and there is little reason not to.
$foo = $_POST["foo"];
Undefined array key! Oh, no! Tragedy! A crime has been committed! Are you kidding? Just set $foo to undefined and let me deal with the consequences, please?I fundamentally disagree with you though. For me, notices are very useful for identifying typos and other coding mistakes that can lead to incorrect behavior.
Consider the following lines of code:
$user_info = array(
'id' => 1,
'username' => 'nbpoole',
'is_guess' => false
);
if (!$user_info['is_guest'])
{
echo 'Member stuff';
}
When I run that script with error_reporting set to E_ALL, I get an "undefined index" notice pointing me to the line where I do the comparison: at that point, I can track down where in my code I misspelled the word guest. Without the notice, I might not immediately realize that the 'is_guest' index was mis-spelled somewhere. $val = array_key_exists('key', $dict) ? $dict['key'] : NULL;
Being able to say "I expect a potentially nil value (and am okay with that)" via get() rather than array index is both semantically useful, and far more beautiful than the PHP equivalent.Python's dict.get is a bit like the getOrElse found in Scala. It's quite handy and can be seen as advanced conceptually.
I actually added some code like that to a recent post about PHP here: http://news.ycombinator.com/item?id=2771304
Ever tried to assign a non-existing variable in another language? I think you will get a compile error.
This isn't too hard:
$foo = isset($_POST["foo"]) ? $_POST["foo"] : null;What about short object declaration syntax:
$obj = { param:'blah' };
PHP already has stdClass, so I doubt it would take much of a parser change to implement that.
Adding fancy syntax does not magically transform that crapware to something almost perfect like python3 or ruby (in its way) where these syntactic forms are among foundations of the language and are supported through all basic idioms. ^_^
Even better would be bool/float/int/string/func ref type hinting...
Slower parsing, really? Is that what you are worrying about?