|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-07-10 04:10 UTC] awilliams at linkme dot com dot au
Description:
------------
I would like to be able to tell if a function was called from a context that is expecting a return value or not. Additionally what type is expected.
eg('hello'); // called not expecting a return value
echo eg('hello').' world'; // called expecting a string
function eg($s)
{
if(return){ // suggested overloading of the return keyword to report the function context.
return ($s);
}
else{
echo $s;
}
}
Additionally
gettype(return);
and
is_string(return);
is_array(return);
etc
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 16:00:02 2025 UTC |
You could pass an additional parameter to the function function ($foo, $return) { if ($return) { return $foo; } else { echo $foo; } } Many people would say that changing the behavior of a function from it's use case is bad. I'm also not sure we can implement this without adding overhead to *all* function calls, which we won't like to do.The reason to expose the calling context is so that the function can confirm it's correct: function calculate_something($args){ if (get_calling_context() == "VOID") { print "ERROR: must be called in non-void context!"; exit; } return do_expensive_calculation($args); } This might be unnecessary in your own code but it's VERY useful when writing libraries. Perl has this function (wantarray) and I use it whenever I write libraries. Yes, this function can be misused, but so can most functions. Overloading the return keyword is a terrible way to implement this. Make it a clearly named function, like get_calling_context. Finally, it would probably be sufficient to simply return void/non-void context, but more specific context is known: print function(); // the RV will be evaluated as a string $a = 3 + function(); // the RV will be treated as a number if (function())); // the RV will be treated as a Boolean etc.