Search code examples
phppythonprogramming-languages

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?


Solution

  • 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.