Search code examples
phpfunctionreturn-valuechaining

Function chaining with different return values?


Is it possible to have a method return different values depending on context (how the return value is used)? For example, could a method return $this when it's then used with the arrow operator to call another method (i.e. chaining method calls), but return a scalar when the return value isn't used this way?

Case 1:

$result = $test->doSomething1(); // returns 4
// $result returns 4

Case 2:

$result = $test->doSomething1()->doSomething2();
// doSomething1() returns $this
// doSomething2() returns 8

Is there anyway to perform such a behaviour?


Solution

  • If I understand the question correctly, you want a method (doSomething1) to return a value based on what the rest of the call chain looks like. Unfortunately, there is absolutely no way you can do this.

    Common programming paradigms shared across "all" languages (how methods, operators and such work in the context of the grammar) dictate that the result of the expression $this->doSomething1() has to be worked out before the result of possibly calling ->doSomething2() on it can be considered. Statically typed and dynamically typed languages do this in different ways, but the common factor is that the expression $this->doSomething1() has to be considered independently of what follows or does not follow.

    In a nutshell: $this->doSomething1() has to return a specific type of value in both cases. And in PHP there is no way to have a type of value that can behave like a number in one context and like an object with methods to call in another.