开发者

Why are functions indexable in Python but not PHP?

I don't mean for this question to be about Python vs PHP but about languages in general. I use Python and PHP as examples because I know them.

In Python we can do mytoken = mystring.split(mydelimiter)[1], accessing the list returned by str.split without ever assigning it to a list. In PHP we must put the array in memory before accessing it, as in $mytokenarray = explode($mydelimiter, $mystring); $mytoken = $mytokenarray[1];. As far as I know it is not possible to do this in one statement as in Python.

What is going on开发者_开发问答 behind this difference?


If you try to do this in php

$mytokenarray = explode($mydelimiter, $mystring)[1];

notice the error you get: Parse error: syntax error, unexpected '['.

This means that php is getting upset when it tries to parse the code, not when it tries to execute it. I suspect that means that php's grammar (which, I hear rumored, is generated on the fly though I really have no idea) says that you can't put '[' after a statement or expression or whatever they call it. Rather, you can probably only put '[' after a variable.

Here's Python's grammar. http://docs.python.org/reference/grammar.html which contains the rule trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME From there you can see that trailer is part of atom which can also contain [. You're starting to get the picture that it's pretty complicated.

Blah blah blah, long story short, learn about compilers, or even better, write one for a toy language. Then you will have loads of insight into language quirks.


It is a design decision the authors of the languages chose to make. Generally spoken (and this is of course not always the case) the nicer the syntax a language has the slower it tends to be. Case in point: Ruby.


This feature is now possible with PHP as of version 5.4.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜