Paolo
Paolo

Reputation: 15827

PHP: know if the function's return value will be used or discarded

Given the function

function sum( $a, $b )
{
   echo $a + $b;
   return $a + $b;
}

It's return value may be used...

$c = sum( 2, 3 );
otherFunction( sum( 4, 5 ) );

...or just discarded.

sum( 6, 7 );

Is there a way to know from the code inside sum() if upon function termination the return value will be used (assigned to a variable/expression or passed to another function) or discarded?

Upvotes: 1

Views: 85

Answers (1)

Mark Reed
Mark Reed

Reputation: 95307

No, I'm afraid not.

There are languages that let you detect the calling context of a function (e.g. Perl has wantarray which will tell you not only if the return value is being assigned, but whether it's expected to be a scalar or list value). But they are the exception; most have no such feature, and PHP is in that camp.

Your function has to just return the value it means to return and leave it up to the caller to either use that returned value or not.

Upvotes: 3

Related Questions