6 ms·
Now if only when a function returns an array we needn't a variable... function boo(){ return array(1,2,3) } echo boo()[1];
by barredo 15y ago
Now if only when a function returns an array we needn't a variable...
function boo(){
return array(1,2,3)
}
echo boo()[1];
- joelhaasnoot 15y agoEspecially since you can do $a->b->c->d
- nbpoole 15y agohttp://svn.php.net/viewvc?view=revision&revision=300266 http://svn.php.net/viewvc?view=revision&revision=300266 http://www.php.net/archive/2011.php#id2011-06-28-1 http://www.php.net/archive/2011.php#id2011-06-28-1 It's in PHP 5.4 alpha as well ;)
- barredo 15y agoThanks!
- whiskers 15y agoIt's not quite what you're asking for, but there is a way to handle array results from functions where you know the number of elements that will be returned. 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 );
- andrewvc 15y agoAh yes, I love nothing more than functions on the left side of assignment. Edit: Yes, it is a special form, but its still irregular, and that makes it shitty.
- abarrett 15y agohttp://www.php.net/manual/en/function.list.php http://www.php.net/manual/en/function.list.php It's a language construct, not a function.
- masklinn 15y ago`list` is a special form, not a function.
- wvenable 15y agoIt's a pretty common feature of a lot of languages (Python, Perl, etc) so it's really not that irregular.
- jrockway 15y agoIt looks more obviously "language feature" in Perl, Python, and JavaScript, though: my ($foo, $bar) = f; (foo, bar) = f() var [foo, bar] = f();
- wvenable 15y agoHow are any of those examples significantly different from: 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.
- paradox95 15y agoI don't see how this will ever be useful. The state "echo boo()[1];" assumes you're only ever going to need that one value from the array. The rest of the array is lost. What if the next line in the code needs index 3 from the array? Now you have to run the function again. 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.
- etherealG 15y agoyou're assuming that cases don't exist where you won't reuse something. this is a false assumption, e.g. if all I wanted was the creation date of a file: stat("filepath")[7] is a reasonable way to do this in php, but you can't currently.