Search code examples
phpoperator-precedence

PHP arrow / method call operator ("->") precedence


I'd like to have a reference stating clearly where PHP's arrow / method call operator (->) falls as regards the order of operator binding.

Unfortunately, the authoritative PHP manual page on operator precedence doesn't list it.

Example where someone could have doubts whether this could throw an exception because $price was first cast to string and only then the method call ->times() attempted:

return (string) $price->times($quantity);

In the answer, please indicate if there was any change here between PHP versions.

Bonus: does the static call (::) operator has the same precedence as ->?


Solution

  • $foo->bar(...) is classified in PHP's grammar as a member-call-expression.

    This is a form of callable-variable, which itself is a form of variable. Essentially, a call to a member function on an object has the same precedence as any other "raw" variable - $foo->bar(...) and just $foo should be treated identically by the compiler. Neither is an "operator", and so they don't fit in the same hierarchy as the ones listed in the manual page you linked.

    For your bonus question, :: is classed as a scoped-call-expression, which holds the same "precedence".