|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-02-11 11:21 UTC] martin at glooware dot com
Description:
------------
Currently it's not possible to use any constants, variables or anonymous functions in a function parameter as default value. This is for example not possible:
function saveUser($name, $surname, $company = CONSTANT_COMPANY_VALUE) {}
... or even this ...
function calculateGravitationalPull($rotation, $axis, $speed, $grav_const = (3.234 / $rotation * $speed)) {}
I've come across various situations, like the example ones above, where I'd love to be able to inject a configuration value or an anonymous function as a function parameter.
Coding this all inside the function is of course also possible. However, this would make it much easier to create some specific functions for which we'd be able to say how the function behaves straight from its own function and parameters documentation.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 24 00:00:01 2025 UTC |
For a more detailed answer: >Currently it's not possible to use any constants, variables or anonymous functions in a function parameter as default value. This is for example not possible: >function saveUser($name, $surname, $company = CONSTANT_COMPANY_VALUE) {} Did you actually test that code sample and check the manual to make sure your assertion was correct‽ You have been able to use constants as default values since PHP 5.3, and that came out 6 years ago. That function you provided? It already works. Plus, since PHP 5.6, constant expressions are supported: function foobar($x = "hello, " . [1, 2, 3][SOME_CONST] / 3 ** 7); It's true that you can't use variables, but that can be easily done in the body of the function.Not for nothin', but HHVM supports any arbitrary expression in the default, even function calls. function foo($bar, $baz = getBaz($bar)) { ... }