I was hoping to start some discussion regarding named parameters. I'm
sorry if it's frowned upon to re-post or re-paste something, but I'm
thinking that perhaps my email (with the subject Re: Hi) was
overlooked on the list in whatever readers, so I'm going to post it
again, this time with a better subject. My apologies if this is
frowned upon, I'm just trying to bring up a discussion about this
issue I'd like to see in PHP 6.
Once again I'd love to create an RFC for this, but I don't think I
have permissions on the wiki to do that. What do I do to get those
privileges granted to my wiki account?
==== original ====
... I've been a PHP developer for
a long time (and before that, C / C++ ) and as I saw code grow and change, I developed design patterns to help ensure maintainability in the long term. In fact, as a founder of a business (and not just a programmer), I value the readability and maintainability of code even more than things like elegance, expressiveness, or programmer talent, because it scales better and is more robust, letting programmers get up to speed.
Anyway I noticed that the following always seems to happen over time: in any project, a set of functions and classes is created, which may or may not become a reusable library. There is code that calls these functions. Over time, the classes get more methods, and the functions may be overloaded to handle more functionality. The classes are designed to expand nicely, and nothing needs to be done. But the functions start looking pretty bad after a few years, because of the parameter mechanism. By necessity, the order of the parameters corresponds to the time at which they are introduced, and not something more logical. Providing defaults for the parameters does very little to mitigate this. Experience has shown that hardly anyone ever predicts at the outset how a library will evolve, and currently function "interfaces" are something that needs to be planned carefully at the start, or else can devolve into some nonsense that requires calls like:
myFunc(3, 4, null, 4, 8, null, "blah")
Besides being hard to follow, it's also cryptic to the reader of the call. We are not sure what the null or 4 corresponds to, without looking up the function definition (perhaps in a tooltip in an IDE).
The solution is simple. I've gotten into a habit of defining almost all my functions like this:
function myFunc($required1, $required2, array $optional = array()) { }
As the function's interface evolves over time, new required parameters cannot be introduced (as it would break the old calls to the function, which may be in the wild). However, functionality can be extended via optional parameters. Also, the calls to the function always look much cleaner:
myFunc(3, 4, array('clean' => true, 'name' => 'title'))
Inside the actual function implementation, I may very well just do: extract($optional). The $optional array can override existing parameters, etc... in fact, I can very easily set some defaults, with either one of these two patterns:
$clean = true; $name = 'default'; extract($optional);
or the javascript-like way:
$defaults = array('clean' => true, 'name' => 'default');
extract(array_merge($defaults, $optional));
So why am I saying all of this? Well, PHP up until 4 had a reputation for lots of bad coding style, spaghetti code, etc. With PHP 5 and better OOP, this reputation has lessened, especially with the great libraries out there (Zend Framework, Kohana, symfony, etc.) But there is still a problem. We (or at least I) would want PHP 6's reputation to be even better, and the reputation is largely based on how maintainable and cost-effective the code is, which is written by programmers actually using PHP. Blaming newbie programmers is one thing, and may even have some truth to it (PHP is simple - thus attracts newbies) but it's always good for a language to steer you in the right direction by default, and make it easier to write maintainable code.
PHP has a great opportunity to do this, by implementing a very simple change, turning all current PHP 5 code, and all code that will be written in the future, into maintainable code. Moreover, it won't break any existing code, like some other additions to PHP 6 might do. This one simple tweak will make PHP 6 code much more reusable and maintainable, just like namespace support will potentially make future PHP code more interoperable without having to write Artificial_Namespace_Class, like ZF and PEAR do.
So here is my proposal. Let's have named parameters. Yes, I know this has been brought up before and rejected -- although I don't know what the discussion was, so I would like to have one in light of what I said above. Other languages have elegant solutions to this ... python, javascript, etc. and yes I realize that a common response is "PHP is PHP and not those other languages". But this might be a short-sighted response, as other languages may have winning features that really make it possible for programmers to write better code, and develop better coding and thinking patterns, at no cost, and we would do well to consider whether PHP could benefit from a feature like that.
I propose we do two things in PHP 6:
- Extend function call syntax and semantics so that providing parameters to a function has exactly the same syntax as creating an array. Namely:
myFunc(3, 4, 'a' => 'b', 'c' => 'd') would be possible, just like array(3, 4, 'a' => 'b', 'c' => 'd')
COMPATIBILITY:
This shouldn't break any userland code in earlier versions of PHP,
because current function calls are simply a subset of the proposed functionality. They will continue to work in exactly the same way, from the point of view of userland.
PROS:
a) Makes understanding the language easier for everyone, since now
there is only one thing to remember rather than two (current docs are a bit hard to grasp regarding references). Two concepts are unified into one, reducing mind clutter. Passing parameters becomes like creating an array, and references are handled nicely within this unified paradigm.
b) Most importantly, makes EVERY function and method extensible as I
described above. No more adding parameters ad-hoc in the order they are dreamed up. Instead, they can be added as named parameters, just like the $optional array I was using above. While programmers can choose to use my design pattern, those that didn't plan out all future versions of the function (let's face it, the majority) still get to reap the advantage of this design pattern, simply via named parameters. Leading to vastly more maintainable code, which is what I am really advocating here.
c) Calls to functions will no longer be cryptic, but actually
descriptive. Compare myFunc(3, 4, null, null, array(), 5) to myFunc(3, 4, 'max' => 5)
CONS:
There is only one I can think of. Named parameters are superior to parameters with default values (foo = "bar") in every way except one: because the defaults are assigned within the function implementation, they have to be documented separately (in DocBlocks, for example). I had someone bring up the objection that code using this design pattern would be less self-documenting. My response is that a) with magic methods, PHP hardly encourages self documenting code anyway, and b) the actual maintainability gains that result from sensible function interfaces will far outweigh whatever negligible benefit one may get from knowing parameter defaults from function signatures. If anything, it'll cause more people to document defaults properly, using DocBlocks or another method.
- Extend func_get_args to be able to return associative arrays.
ANALYSIS:
This shouldn't break existing function calls, and here's why. Old versions of the function won't use this feature, so function calls to them won't need to change, either. New versions of the function will be written after this feature is introduced (i.e. in PHP6), so will be aware of the possibility of named parameters. Old calls to new versions of the function simply won't use the feature, so they won't need to change, either. New calls to new versions of the function have the option of using the feature, or not. So nothing is broken at all, but new functionality is there for you to use in PHP6.
PROS:
a) This once again makes PHP more elegant and unified. One of PHP's
most notorious / cool features is that it lets you use array() for both numerically indexed arrays and associative arrays (a.k.a. maps, hashes, dictionaries, etc.) Why not weave this into PHP function calls as well? PHP is so function oriented. And this would give developers a lot of expressive power while at the same time promoting better code and the maintainability we talked about. I personally feel it's purely awesome whenever an extension is able to achieve both of those.
b) Lots of PHP programmers also work with Javascript. This would make
them happy -- they can use what they consider to be a very useful coding pattern in JS (jQuery and most other popular frameworks use it), and start doing it in PHP:
function myFunc($a, $b) {
$id = uniqid();
$title = 'People hi';
extract(func_get_args()); // possibly overriding the parameters }
CONS:
a) Maybe there are some internal problems to implementing this, so
serious that it's infeasible?
b) Will this break any PECL extensions? If so, are we planning to
maintain compatibility with all PECL extensions written for earlier versions of PHP? Is it worth it to introduce this feature?
What do you guys think? I really want PHP 6 to rock and have an even better reputation among businesses, programmers, etc.
Sincerely,
Greg Magarshak
Hi!
I really doubt named parameters would have much of an impact on anything, but I'd be willing to consider it if a clean implementation was to show up.
I think they'd allow to manage complex parameter sets more efficiently than with those $options arrays. But that'd probably require changing the way how parameters are passed, since the stack won't work too good anymore for it.
Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/
(408)253-8829 MSN: stas@zend.com
I think they'd allow to manage complex parameter sets more efficiently than with those $options arrays. But that'd probably require changing the way how parameters are passed, since the stack won't work too good anymore for it.
FWIW, named parameters would be a great aid in building uncoupled systems—particularly when some of the tiers are not based on PHP.
I really doubt named parameters would have much of an impact on anything, but I'd be willing to consider it if a clean implementation was to show up.
I think they'd allow to manage complex parameter sets more efficiently than with those $options arrays. But that'd probably require changing the way how parameters are passed, since the stack won't work too good anymore for it.
Is the desire for named parameters to only have it for user land function/methods? If so, I am kind of -.5 on this because that would be a little WTF for a new user.
If not, then it is a huge undertaking as every internal function and pecl extension would have to be updated to support them. In which case it is a ton of work.
I have long ago started passing arrays and doing validation myself, which sucks. I admit, named parameters + scalar type hints would be quite nice and simplify a lot of my code.
Brian.
I don't think thad would require thad much work. we allready have arginfo that does type hinting...
Modifieing that to support rewrtiting param order based on reflection Info shouldn't be that hard...
The problem however is when an function accepts varargs (usually named "...")..... if we however bring in strictct-ish naming convention I don't see any immediate problems....
Hi!
Quoted text · 4 lines
I really doubt named parameters would have much of an impact on > anything, but I'd be willing t...
I think they'd allow to manage complex parameter sets more efficiently than with those $options arrays. But that'd probably require changing the way how parameters are passed, since the stack won't work too good anymore for it. --
Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/
(408)253-8829 MSN: stas@zend.com
-- To unsubscribe,
visit: http://www.php.net...
Hi!
The problem however is when an function accepts varargs (usually named "...")..... if we however bring in strictct-ish naming convention I don't see any immediate problems....
Varargs shouldn't be a problem and we don't even need ... there - we can just assume every function has implicit ... at the end (more or less what we are doing now). We have the following issues to overcome now:
-
We don't keep the name information on the receiving end. It should be pretty easy to fix - the parser knows the variable names. So instead of a number RECV opcode can just get a name, or maybe have separate name table that corresponds to numbers.
-
We don't have a way to pass the name information on the sending end - right now we use stack, which would not go well with named params. We'd probably have to switch to a hashtable - which would require substantial change to parameter change/receive code - but should be doable. Though introducing a hashtable may have performance impact there.
-
Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover, catching this situation can be non-trivial, as right now parsing nested function calls may not keep enough context for this.
-
varargs can be dealt with by either extending
func_get_args()to provide name information or maybe by having some function that returns only those args that do not have matching names (that would make generic options easier to do).
--
Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/
(408)253-8829 MSN: stas@zend.com
Those are some good points. I would say with regard to 3, that we have the same problem (sic) with defining arrays in PHP, in terms of it not being clear what results from array(1, 2, 'a' => $b, 4). Although we could perfectly copy the array definition semantics, I think you're right, that abc(1, 2, 'a' => $b, 3) is not really useful in the first place. So with that in mind, we could stop perfectly duplicating "array definition semantics", and instead have the following:
a) Regular parameters cannot appear after named parameters, i.e. abc(1, 2, 'a' => $b) is fine but abc(1, 'a' => $b, 2) is not
b) Because of this, we can easily see where the named parameters start (and indeed if they are present in the call). Then, you can implicitly add a variable to the end of the stack which points to a hash, which contains the named parameters.
c) Then, func_get_args would be extended to check for the presence of this hash, and when it's there, simply merge it on top of the array it would have returned. Thus, if the function was abc($a) and I called it with abc(4, 'a' => 3) then func_get_args() inside abc would give array(0 => 3, 'a' => 3).
The question I have is if we are not copying the array semantics anymore, whether we should have abc('a' => 3) or abc(a => 3). I personally would prefer 'a' => 3 because that allows for variable parameter names.
Greg
Stanislav Malyshev wrote:
Quoted text · 12 lines
Hi!
The problem however is when an function accepts varargs (usually named "...")..... if we however bring in strictct-ish naming convention I don't see any immediate problems....
Varargs shouldn't be a problem and we don't even need ... there - we can just assume every function has implicit ... at the end (more or less what we are doing now). We have the following issues to overcome now:
We don't keep the name information on the receiving end. It should be pretty easy to fix - the parser knows the variable names. So instead of a number RECV opcode can just get a name, or maybe have separate name table that corresponds to numbers.
We don't have a way to pass the name information on the sending end
- right now we use stack, which would not go well with named params. We'd probably have to switch to a hashtable - which would require substantial change to parameter change/receive code - but should be doable. Though introducing a hashtable may have performance impact there.
Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover, catching this situation can be non-trivial, as right now parsing nested function calls may not keep enough context for this.
varargs can be dealt with by either extending
func_get_args()to provide name information or maybe by having some function that returns only those args that do not have matching names (that would make generic options easier to do).
err, sorry, to correct my example:
function abc($a) {
var_export(func_get_args());
}
abc(4, 'a' => 3);
would output array(0 => 4, 'a' => 3)
Greg
Gregory wrote:
Quoted text · 18 lines
Those are some good points. I would say with regard to 3, that we have the same problem (sic) with defining arrays in PHP, in terms of it not being clear what results from array(1, 2, 'a' => $b, 4). Although we could perfectly copy the array definition semantics, I think you're right, that abc(1, 2, 'a' => $b, 3) is not really useful in the first place. So with that in mind, we could stop perfectly duplicating "array definition semantics", and instead have the following:
a) Regular parameters cannot appear after named parameters, i.e. abc(1, 2, 'a' => $b) is fine but abc(1, 'a' => $b, 2) is not
b) Because of this, we can easily see where the named parameters start (and indeed if they are present in the call). Then, you can implicitly add a variable to the end of the stack which points to a hash, which contains the named parameters.
c) Then, func_get_args would be extended to check for the presence of this hash, and when it's there, simply merge it on top of the array it would have returned. Thus, if the function was abc($a) and I called it with abc(4, 'a' => 3) then
func_get_args()inside abc would give array(0 => 3, 'a' => 3).The question I have is if we are not copying the array semantics anymore, whether we should have abc('a' => 3) or abc(a => 3). I personally would prefer 'a' => 3 because that allows for variable parameter names.
Greg
Stanislav Malyshev wrote:
Hi!
The problem however is when an function accepts varargs (usually named "...")..... if we however bring in strictct-ish naming convention I don't see any immediate problems....
Varargs shouldn't be a problem and we don't even need ... there - we can just assume every function has implicit ... at the end (more or less what we are doing now). We have the following issues to overcome now:
We don't keep the name information on the receiving end. It should be pretty easy to fix - the parser knows the variable names. So instead of a number RECV opcode can just get a name, or maybe have separate name table that corresponds to numbers.
We don't have a way to pass the name information on the sending end - right now we use stack, which would not go well with named params. We'd probably have to switch to a hashtable - which would require substantial change to parameter change/receive code - but should be doable. Though introducing a hashtable may have performance impact there.
Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover, catching this situation can be non-trivial, as right now parsing nested function calls may not keep enough context for this.
varargs can be dealt with by either extending
func_get_args()to provide name information or maybe by having some function that returns only those args that do not have matching names (that would make generic options easier to do).
Hi,
I'm not fully convinced we really need it, I had some moments in the past where I wished they existed, but always found good solutions.
That said:
The question I have is if we are not copying the array semantics anymore, whether we should have abc('a' => 3) or abc(a => 3). I personally would prefer 'a' => 3 because that allows for variable parameter names.
Allowing variable parameter names means allowing any expression (else it gets messy with inconsistent rules) which means that we allow a very flexible syntax which might lead to code that's hard to understand. If you don't know which parameters you want to provide maybe an array is the better option. With such a syntax I expect more abuse than useful use of the feature.
For do_something(parameter => 23); we have the benefit, that IDEs could easily validate that which prevents typos and provide aid. But then I'm not sure this fits to the language either as we always expect quoted names. And from the some distance this looks like a constant used used as parameter name, as in
<?php
const foo = 42;
$a = array(foo => 'bar');
do_something(foo => 'bar');
?>
Another possible limitation there is that our parser won't allow keywords there. An example where this might be annoying might be something along these lines:
<?php
function getInstance($param1 = 1, $param2 = 2, $class = 'default_class' {
$r = new ReflectionClass($class);
return $r->createInstance($param1, $param2);
}
getInstance(class => 'my_class');
?>
Just some random thoughts, maybe somebody has a better syntax, maybe that's just me,
johannes
hi,
- Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover, catching this situation can be non-trivial, as right now parsing nested function calls may not keep enough context for this.
If we introduce named argument, mixing them should not be weird. An argument can have both a name and a position, allowing combination of normal or named arguments. Python's way to do it is very nice and handy:
http://diveintopython.org/power_of_introspection/optional_arguments.html
I did not look at the parser implementation or limitation lately, but it would rock if we can use the same syntax than python. It should not conflict with any existing syntax (foo($a = 1) already works, with operator precedence). Again, if the parser allows it :)
I also don't see another way to do it than using a hash (or similar constructs) which will certainly have a significant impact on performance.
Cheers,
Pierre
@pierrejoye | http://blog.thepimp.net | http://www.libgd.org
A small comment: I don't think named parameters should seriously affect performance if we check for their presence during the call. That is to say, if a call has no named parameters, use what we use now. Otherwise, push an extra hash variable on to the end of the stack. Creating this hash variable should be no more overhead than if the user manually passed in an array() as the last parameter.
Johannes: yeah I think I strongly prefer $parameter => 23. Like you said, it looks like a constant if we used f(parameter=>23) . In fact, arrays with arbitrary keys are useful and PHP already has $arr['foo-bar'], ${'foo-bar'} and $baz->{'foo-bar'}, so f('parameter' => 23) is not such a stretch. Especially since func_get_args returns an array. There is only one case where things get a little hairy, and that's f(2, '0' => 4) which will probably make func_get_args() return array(4) ... just as array(2, '0' => 4) would return array(4).
Greg
Hi!
http://diveintopython.org/power_of_introspection/optional_arguments.html
This approach could work too, except that simple literal means constant in PHP, unlike Python. So array syntax might be more natural, but both can work I guess.
--
Stanislav Malyshev, Zend Software Architect stas@zend.com http://www.zend.com/
(408)253-8829 MSN: stas@zend.com
- Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover,
If we introduce named argument, mixing them should not be weird. An argument can have both a name and a position, allowing combination of normal or named arguments. Python's way to do it is very nice and handy:
http://diveintopython.org/power_of_introspection/optional_arguments.html
Just to be clear about this: Python does not allow using an unnamed parameter after a named parameter occurred, i.e. foo(bar = 3, 2) is not valid there.
I would go as far as disallowing mixing of named and unnamed parameters completely. But that's probably just me.
- Martin
Quoted text · 4 lines
- Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be trouble, since it is not clear at all where 4 should go to. Moreover,
If we introduce named argument, mixing them should not be weird. An argument can have both a name and a position, allowing combination of normal or named arguments. Python's way to do it is very nice and handy:
http://diveintopython.org/power_of_introspection/optional_arguments.html
Just to be clear about this: Python does not allow using an unnamed parameter after a named parameter occurred, i.e. foo(bar = 3, 2) is not valid there.
Right, the doc is clear about that and makes the whole thing less confusing.
I would go as far as disallowing mixing of named and unnamed parameters completely. But that's probably just me.
That would defeat the main purposes of named arguments.
Cheers,
Pierre
@pierrejoye | http://blog.thepimp.net | http://www.libgd.org
In the case whereby names parameters are "plucked" from the argument list and passed as a hash to the function it really shouldn't matter whether that's invalid in python; both (2, 'name' => 'test') and ('name' => 'test', 2) would yield the same results, albeit it's a highly dubious way of passing arguments ;-)
Quoted text · 8 lines
- Combining named and un-named params can get weird - i.e. foo(1,2,3) is simple, foo(1, 2, bar => 3) is doable, but foo(1, 2, bar => 3, 4) would be
trouble, since it is not clear at all where 4 should go to. Moreover,If we introduce named argument, mixing them should not be weird. An argument can have both a name and a position, allowing combination of normal or named arguments. Python's way to do it is very nice and handy:
http://diveintopython.org/power_of_introspection/optional_arguments.html
Just to be clear about this: Python does not allow using an unnamed parameter after a named parameter occurred, i.e. foo(bar = 3, 2) is not valid there.
I would go as far as disallowing mixing of named and unnamed parameters completely. But that's probably just me.
- Martin
--
--
Tjerk
Tjerk Anne Meesters wrote:
In the case whereby names parameters are "plucked" from the argument list and passed as a hash to the function it really shouldn't matter whether that's invalid in python; both (2, 'name' => 'test') and ('name' => 'test', 2) would yield the same results, albeit it's a highly dubious way of passing arguments ;-)
Actually we use "positional" (scalar) both after and before "named" (associative) parameters a lot for HTML generation and DB queries:
$html = table('class' => "beautiful",
tr(
td("foo"), td("bar"),
),
tr(
td("qux"), td("quux"),
),
);
foreach (new T_User('firstname' => $firstname, "ORDER BY age") as $user) ...
$bar = it::replace('Foo' => "Bar", $foo, 'casesensitive' => true);
So any solution restricting named parameters to any of
- declared named parameters only
- not allowing alternating named/positional parameter sets while maintaining these sets and order
would not fit our needs.
As a result our patch (and syntax converter in both directions for unpatched webservers) uses a simple but somewhat limited approach: Any sequence of key => value pairs in a function call are surrounded by array() (done at compile time). This means functions accepting interleaved named/non-named parameters need to do some varargs parsing and sometimes you need to still manually add array() if you want to separate two sets of named parameters (but that's a questionable API in most cases).
More info: http://cschneid.com/php/INFO_README Patch and manual converter: http://cschneid.com/php/ Autoloader with automatic syntax conversion: http://itools.search.ch/
I know I've mentioned this here before but I still think its pros and cons should be taken into consideration when talking about this subject,
- Chris
my gut feeling also says that we shouldnt allow positional arguments after named parameters. just picking out one of your examples ..
foreach (new T_User('firstname' => $firstname, "ORDER BY age") as $user)
couldnt this also be written as:
foreach (new T_User('firstname' => $firstname, "ORDERBY" => "age") as $user)
of course it would be a bit more work when constructing the final query, but its tons clearer in terms of knowing how to use the API with just reading one use of the API and not the actual implementation.
in the above code what is the purpose of the positional argument? can i just "append" what I want? aka is the idea of the API to also support
foreach (new T_User('firstname' => $firstname, "LIMIT 100") as $user)
and
foreach (new T_User('firstname' => $firstname, "ORDER BY age LIMIT 100") as $user)
in that case it would still be better to then do:
foreach (new T_User('firstname' => $firstname, 'append' => "ORDER BY age") as $user)
.. of course its a few more characters, but its definitely easier to grasp whats going on, then having to parse what is named and what is positional.
i am trying to remember what killed the discussion last time around. i think it was concerns over having to convert all internal functions, but i guess that was before we unified the parameter parsing API. IIRC hartmut was quite involved in the discussion back then .. maybe he remembers.
regards,
Lukas Kahwe Smith
mls@pooteeweet.org
Once again I'd love to create an RFC for this, but I don't think I have permissions on the wiki to do that. What do I do to get those privileges granted to my wiki account?
Hmm thought I already mailed you about this .. anyways the link is here (can be found by clicking on "login" on the lower right navi bar): http://wiki.php.net/start?do=register
regards,
Lukas Kahwe Smith
mls@pooteeweet.org