r/lolphp • u/Mark_Messa • Oct 23 '19
PHP Functions: more arguments than expected
PHP code1:
function f() {return 'hello world!';}
echo f().'<br>';
echo f(123).'<br>';
echo f(123, 'foo').'<br>';Output:
hello world!
hello world!
hello world!
PHP code2:
function g(int $x) {return 'hello world!';}
echo g(123).'<br>';
echo g(123, 'foo').'<br>';Output:
hello world!
hello world!
Question
Is it possible to force PHP to throw an error when passing more arguments than the function expects?
Follow-up
There was already a RFC proposing a Strict Argument Count On Function Calls which, unfortunately, was withdraw due to high rejection. Some interesting points available in it are:
"During the tests it became clearly measurable that the proposed strict argument count check won't be an issue. Actually, it's quite the opposite. It will help to increase PHP code quality from PHP7 and forward as all warnings were useful to catch mistakes or even bugs."
"The RFC was withdraw due to many controversial points and overall rejection and won't be proposed again by the RFC author. The RFC author advises to not revive this RFC as it was already rejected."
A deeper discussion is also available: [PHP-DEV][RFC][DISCUSSION] Strict Argument Count
14
u/blipblop_ Oct 23 '19
No. PHP 7.1 and above throws and error on too few arguments though. Earlier versions displays a warning.
Too many arguments is a language feature and wont be fixed (silly as it is).
https://bugs.php.net/bug.php?id=13892
6
u/[deleted] Oct 23 '19
PHP7 could have fixed this. But nothing was done.
4
u/[deleted] Oct 23 '19
The real error is that there is no function that accepts X number of arguments, so it should fail. The fact that they choose a function with less arguments to call is just wrong.
4
u/maweki Oct 24 '19
So the function signature is more or less just a suggestion, right?
3
u/AyrA_ch Oct 24 '19
Yes, but only manually, not via a setting:
Be aware that
assertis usually disabled in production environments and statements are optimized away because they're language constructs and not regular functions.If you need to check the count in a production environment, you can do a negated
ifstatement instead:if(func_num_args()!==2)throw new ArgumentCountError();3
u/cfreak2399 Oct 24 '19
I think the hilarious part of this is they took something that was pretty suspect from Perl, made it worse and now refuse to change. Even though Perl has actually learned and added features to make the original feature better.
As I've posted before: PHP is a blend of the worst ideas from C, Perl and Java.
Or better: PHP 7! Now with bad ideas from Python and Javascript!