16 ms·
Better than parameter skipping would be named parameters so you could just do: function foo($a, $b="10", $c="5", $d="3") { /* .. */ } foo(5, $c="10");
by leftnode 14y ago
Better than parameter skipping would be named parameters so you could just do:
function foo($a, $b="10", $c="5", $d="3") { /* .. */ }
foo(5, $c="10");
That way $a == 5, $b == "10", $c == "10", and $d == "3". Much better and cleaner syntax in my opinion and a lot of other languages support something similar.
- debacle 14y agoI agree, named parameters are useful as well, but there's no reason that both shouldn't be implemented. The problem with PHP is that, due to the nature of the interpreter, so many of these things are written as syntactical sugar which means that their implementations usually leave much to be desired.
- gilini 14y agoThat's exactly what I was going to say. The author says this about parameter skipping: Personally I’m not particular fond of this proposal. In my eyes code that needs this feature is just badly designed. Functions shouldn’t have 12 optional parameters. I'm not fond of this proposal either, for it doesn't solve a problem named parameters do, which is that sometimes function parameters don't have a logical order, and cramming them into an array feel sloppy as hell.
- ircmaxell 14y agoThe problem with that is it's already valid syntax with a different meaning. function foo($a, $b = "10", $c = "20") {} foo(1, $c=20); var_dump($c); // int(20) The syntax would have to be unambiguous. Perhaps: foo(5, c: 30) or foo(5, $c: 30); or foo(5, $c => 30) or something like that...
- Joeri 14y agoWhat people end up doing in practice is passing in arrays with key/value pairs. The => syntax would be the closest thing to the current way of doing things, except you'd get default values and type hinting. I'm all for it! I'm still looking for a good way to combine array parameters with defaults and hinting in PHP 5.3. I've had some success using DTO's for primary API's: function foo(SomeDTO $data) { ... } foo(new SomeDTO(array("a" => "foo", "b" => 10))); class SomeDTO extends BaseDTO { /** @var string @maxlength 10 */ public var $a; /** @var int */ public var $b = 20; } The BaseDTO class uses reflection to parse the doc comments and figure out how to validate and set its input. It's the same idea as validation annotations in java. It works, but it's quite a heavy syntax, and I wish I had a lighter-weight alternative. I like PHP's loose typing inside an API's class, but when interfacing between API's I want strict typing.
- soulclap 14y agoMaybe I am missing something but never seen that in practice (the 'foo(1, $c=20)' bit), that's a really odd way to initialize a variable. Wouldn't mind if they change it, so that it breaks (with a warning or error). Or have you seen this syntax a lot?