Hi folks,
I just got on the list -- I've been a big fan of PHP for several
years and am throughly enjoying PHP 5. Good work folks, and once I
can get 5.1 set up on my OS X box I'm sure it's be even better.
I've been very interested in hearing about PHP 6 feature discussions,
and the meeting notes that Derrick posted looked really good. But
there was one item that stood out for me as being extremely
disappointing, and that was the curt dismissal of named arguments (or
parameters I guess you are calling them).
Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys
of named arguments, and it is something I've desperately wanted in
PHP for ages. I'm sure I'm not alone in this. I've tried array
constructs, multiple arguments with string-based names and fancy
parsing using func_get_args()
, and various combinations thereof, and
nothing is a good substitute for the real deal.
If I had the technical knowhow to jump in and help implement this, I
would, but I'm a lousy C programmer. :( But I definitely want to lend
my support to anyone interested in working on this. Please, please
don't give up on this feature!
Thanks so much,
Jared
Can you explain your reasoning behind "essential for using PHP as a
solid templating language" and "nothing is a good substitute for the
real deal"?
- Andrei
Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys of
named arguments, and it is something I've desperately wanted in PHP
for ages. I'm sure I'm not alone in this. I've tried array constructs,
multiple arguments with string-based names and fancy parsing using
func_get_args()
, and various combinations thereof, and nothing is a
good substitute for the real deal.
Can you explain your reasoning behind "essential for using PHP as a
solid templating language" and "nothing is a good substitute for
the real deal"?
- Andrei
OK, to take an example from Smarty, you could do a value cycle (for
multi-row-color tables, etc.) with some extra parameters like so:
{cycle name="myCycle" values="#eeeeee;#d0d0d0" print=false
reset=true delimiter=";"}
(I'm not a Smarty expert, so I apologize if I didn't get that quite
right.)
Now, if I wanted to express that with a PHP function currently, it
might look like this:
cycle("myCycle", "#eeeeee;#d0d0d0", false, true, ";");
My question is, what if you have no idea how the cycle function
works, or you haven't used it in a while and temporarily forgot? Your
two options are look at the source code (if possible) or look at the
documentation (if it's any good). Whereas with named arguments, it's
self-explanatory.
cycle(name: "myCycle", values: "#eeeeee;#d0d0d0", print: false,
reset: true, delimiter: ";");
(FYI: I just picked a colon for the heck of it...whatever operator is
used isn't important to me.)
Much, much clearer and obvious. Perhaps not such a big deal in
"regular" PHP code blocks, but in an HTML/PHP mixed template type of
scenario, the named arguments are so much nicer. Plus, if they're
implemented in an order-agnostic fashion, you could reorder those
arguments any way you like -- but I don't necessarily think that's
its biggest selling point.
Sure, you could use an array for this, like so:
cycle(array("name" => "myCycle", "values" => "#eeeeee;#d0d0d0",
"print" => false, "reset" => true", "delimiter" => ";"));
But not only is that a lot more verbose and messy, but it provides no
language features in the function/method definition itself, so you
just have to hope the big array that comes in has the right stuff in
it. Not ideal.
Anyway, I hope that helps, and if you have any other thoughts or
questions, please shoot away.
Regards,
Jared
Hi Jared,
If probably don't understand named arguments correclty but couldn't you
do something like:
function(array('name1' => 'val1', 'name2' => $var));
In the function you could then check which keys (names) have values,
thereby simulating a form of named agruments?
Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys of
named arguments, and it is something I've desperately wanted in PHP
for ages. I'm sure I'm not alone in this. I've tried array constructs,
multiple arguments with string-based names and fancy parsing using
func_get_args()
, and various combinations thereof, and nothing is a
good substitute for the real deal.
Sorry... Forget I said that...
Bart de Boer wrote:
Hi Jared,
If probably don't understand named arguments correclty but couldn't you
do something like:function(array('name1' => 'val1', 'name2' => $var));
In the function you could then check which keys (names) have values,
thereby simulating a form of named agruments?Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys
of named arguments, and it is something I've desperately wanted in
PHP for ages. I'm sure I'm not alone in this. I've tried array
constructs, multiple arguments with string-based names and fancy
parsing usingfunc_get_args()
, and various combinations thereof, and
nothing is a good substitute for the real deal.
You could use an associative array, but then you have a not-so-clean syntax
and you have to handle default values for missing parameters yourself.
Named parameter example:
<?php
function adduser(username: $username, password: $password, superuser:
$superuser=false)
{
// now do some stuff with $username, $password and $superuser
}
adduser('root', 'abcdefg', true);
// or:
adduser(username: 'root', password: 'abcdefg', superuser: true);
?>
Traditional named example:
<?php
function adduser($params)
{
if (!is_array($params)) throw new Exception('No named parameters');
if (!isset($params['username'])) throw new Exception('Missing parameter:
username');
if (!isset($params['password'])) throw new Exception('Missing parameter:
username');
if (!isset($params['superuser'])) $params['superuser'] = false;
// now do some stuff with $params
}
adduser(array('username' => 'root', 'password' => 'abcdefg', 'superuser'
=> true));
?>
You see the big advantages of named parameters?
-
clean syntax
-
no array handling inside the function or method
-
no checking on the existance or non-existance of parameters
-
no forcing default values for missing parameters
-
when you need to skip a parameter, you no longer have to give it's default
value when calling the function, you can simply skip the whole parameter:function foo(bar: $bar=0, bla: $bla='test', cow: $moo='moooo');
call:
foo(cow: 'test');
foo(0, 'test', 'test');
Named parameters would kick serious butt :)
- Ron
"Bart de Boer" bart@mediawave.nl schreef in bericht
news:2D.57.14828.3453E834@pb1.pair.com...
Hi Jared,
If probably don't understand named arguments correclty but couldn't you do
something like:function(array('name1' => 'val1', 'name2' => $var));
In the function you could then check which keys (names) have values,
thereby simulating a form of named agruments?Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys of
named arguments, and it is something I've desperately wanted in PHP for
ages. I'm sure I'm not alone in this. I've tried array constructs,
multiple arguments with string-based names and fancy parsing using
func_get_args()
, and various combinations thereof, and nothing is a good
substitute for the real deal.
I have to admit, although you could do it other ways, it wouldn't be as
clean as what you're proposing. Especially handy for when you just want
to pass on that last parameter without having to pass on all the
forgoing parameters. I'd consider it a nice-to-have.
As for the syntax. I'd like to propose it as follows (syntax-wise):
somefunction($var, $var2, $var3, $var4 = 'val4', $var5) {}
Syntax for calling it with named arguments:
somefunction($var3 = 'val3', $var5 = $othervar = 'val5');
Or it may be confusing to use '$' in front of the names. (I was looking
for consistency with the way you define a function.) So perhaps like this:
somefunction(var3 = 'val3', var5 = $othervar = 'val5');
Only now I'm wondering. Since the PHP engine would have to check for
named arguments for each function. Wouldn't this performancewise cause
too much overhead on function calls?
Ron Korving wrote:
You could use an associative array, but then you have a not-so-clean syntax
and you have to handle default values for missing parameters yourself.Named parameter example:
<?php
function adduser(username: $username, password: $password, superuser:
$superuser=false)
{
// now do some stuff with $username, $password and $superuser
}adduser('root', 'abcdefg', true);
// or:
adduser(username: 'root', password: 'abcdefg', superuser: true);
?>Traditional named example:
<?php
function adduser($params)
{
if (!is_array($params)) throw new Exception('No named parameters');
if (!isset($params['username'])) throw new Exception('Missing parameter:
username');
if (!isset($params['password'])) throw new Exception('Missing parameter:
username');
if (!isset($params['superuser'])) $params['superuser'] = false;// now do some stuff with $params
}
adduser(array('username' => 'root', 'password' => 'abcdefg', 'superuser'
=> true));
?>You see the big advantages of named parameters?
clean syntax
no array handling inside the function or method
no checking on the existance or non-existance of parameters
no forcing default values for missing parameters
when you need to skip a parameter, you no longer have to give it's default
value when calling the function, you can simply skip the whole parameter:function foo(bar: $bar=0, bla: $bla='test', cow: $moo='moooo');
call:
foo(cow: 'test');
foo(0, 'test', 'test');Named parameters would kick serious butt :)
- Ron
"Bart de Boer" bart@mediawave.nl schreef in bericht
news:2D.57.14828.3453E834@pb1.pair.com...Hi Jared,
If probably don't understand named arguments correclty but couldn't you do
something like:function(array('name1' => 'val1', 'name2' => $var));
In the function you could then check which keys (names) have values,
thereby simulating a form of named agruments?Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs. My experience
with both Objective-C and Python has showed me the wonders and joys of
named arguments, and it is something I've desperately wanted in PHP for
ages. I'm sure I'm not alone in this. I've tried array constructs,
multiple arguments with string-based names and fancy parsing using
func_get_args(), and various combinations thereof, and nothing is a good
substitute for the real deal.
Ron Korving wrote:
Named parameter example:
Your example misses the main advantage of named parameters IMHO: Sets of
parameters you don't want to or can't explicitely list because they are
not know yet.
function adduser($params)
{
if (!is_array($params)) throw new Exception('No named parameters');
if (!isset($params['username'])) throw new Exception('Missing parameter:
username');
if (!isset($params['password'])) throw new Exception('Missing parameter:
username');
if (!isset($params['superuser'])) $params['superuser'] = false;// now do some stuff with $params
}
adduser(array('username' => 'root', 'password' => 'abcdefg', 'superuser'
=> true));
This is not how we use named parameters at all. If you have a finite set
of fixed parameters then positional parameters are working just fine.
One of the main advantages lies in a catch-all parameter which gets all
unassignable parameters. While this opens the door for typos even a
whips'n'chains language like Python added this feature because it is
just too useful to omit if you have named parameters :-)
Our use case is something along the lines of (not the actual code, so
don't comment on anything specific here ;-)):
function tag($name, $p = array())
{
foreach ($p as $key => $value)
{
if (is_int($key))
$content .= $value;
else
$attributes .= " $key='$value'";
}
return "<$name$attributes>$content</$name>";
}
function a($p = array())
{
return tag("a", $p);
}
...
echo a(array('href' => $url, 'title' => $title));
or with our patch to make array() obsolete
echo a('href' => $url, 'title' => $title);
Now something like
echo a(href: $url, title: $title, 'non-identifier-chars': 42);
would be even neater, agreed ;-)
- Chris
Ron Korving wrote:
Named parameter example:
Your example misses the main advantage of named parameters IMHO:
Sets of parameters you don't want to or can't explicitely list
because they are not know yet.function adduser($params)
{
if (!is_array($params)) throw new Exception('No named
parameters');
if (!isset($params['username'])) throw new Exception('Missing
parameter: username');
if (!isset($params['password'])) throw new Exception('Missing
parameter: username');
if (!isset($params['superuser'])) $params['superuser'] = false;
// now do some stuff with $params
}
adduser(array('username' => 'root', 'password' => 'abcdefg',
'superuser' => true));This is not how we use named parameters at all. If you have a
finite set of fixed parameters then positional parameters are
working just fine.
Well, I wouldn't say that. The problem isn't that positional
parameters don't work fine -- they do -- but that upon code
inspection you don't know what those parameters are for unless you
know the function/method API ahead of time. Sure, as you pointed out
there are some juicy features you get with named parameters if you
implement them throughly, but I still say its main selling point is
that the calling code is its own API documentation.
Regards,
Jared
I still say its main selling point is
that the calling code is its own API documentation.
why don't you just write something like
cycle(/* name: / "myCycle", / values: / "#eeeeee;#d0d0d0", /
print: / false,
/ reset: / true, / delimiter: */ ";");
It's just as self-explanatory and you don't have to change the
language for it :-)
--Sebastian
I still say its main selling point is
that the calling code is its own API documentation.why don't you just write something like
cycle(/* name: / "myCycle", / values: / "#eeeeee;#d0d0d0", /
print: / false,
/ reset: / true, / delimiter: */ ";");It's just as self-explanatory and you don't have to change the
language for it :-)
Hmm, that's not such a crazy idea. :)
Wait, hey, that's not fair! Now you've spoiled everything! :)
Seriously though, it still doesn't address the fact that the function/
method definition itself needs to have the named parameter notation
to match, plus the idea of the catch-all parameters (from
func_get_args()
presumably) having string keys (I think that's what
Christian mentioned which is a cool Python feature).
Jared
Jared White wrote:
Named arguments are absolutely essential for using PHP as a solid
templating language, and, in fact, they also greatly enhance code
readability for complex method calls of in-depth APIs.
I agree.
As useful functions tend to increase in complexity over time, often so
does the number of parameters.
It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last option.
Sure, you can fall back to associative array parsing. However, I feel it
lacks the rigor that named parameters can give. Named parameters also
give a clean method for the user to see the available options, rather
than reading through source code.
I'd really like this issue to be given more consideration. It's been
brought up consistently over the last couple of years, in some cases
rather passionately (I believe someone wanted to fork PHP over this a
while back). We have a long time before a PHP6 release, this is the
ideal time to discuss implementation.
Kind regards,
Aidan Lister
As useful functions tend to increase in complexity over time, often so
does the number of parameters.It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last
option.
If you get to the point where your function has a dozen parameters, I
would suggest re-thinking the purpose and design of such a function,
because you are likely trying to make it do too much.
-Andrei
Andrei Zmievski wrote:
As useful functions tend to increase in complexity over time, often so
does the number of parameters.It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last
option.If you get to the point where your function has a dozen parameters, I
would suggest re-thinking the purpose and design of such a function,
because you are likely trying to make it do too much.-Andrei
In a simple highlighting function I wrote (which at 16k hits is probably
considered useful) I needed most of the following parameters:
$text
$needle
$strip_links
$case_sensitive
$whole_word_only
$simple_text_only
$highlight_pattern
$return_or_print
$use_xhtml
$tooltips_or_divs
I imagine any function dealing with html may use a significant portion
of these. Obviously some of these are for effect, but I think my point
is clear enough.
We've discussed other options at developers disposal like associative
arrays, setOpt and getOpt functions in a class, but again each have
their drawbacks and named parameters solve the problem elegantly.
Could we properly discuss the pros and cons of a name parameters
implementation - even if it's only to put the whole issue to bed once
and for all?
Best wishes,
Aidan
Hello Aidan,
I think named parameters would be a useful feature... I'll leave it
at that.
Here is a coding idea for you, in case you hadn't considered it...
function highlight($text=NULL, $needle=NULL, $strip_links=NULL, ...)
{
is_null($text) && $text = SOME DEFAULT VALUE;
is_null($needle) && $text = SOME DEFAULT VALUE;
is_null($strip_links) && $text = SOME DEFAULT VALUE;
...
}
In that way, the user doesn't have to remember the default values,
just the offsets.
Best wishes with the proposal.
--
Best regards,
Jason mailto:jason@ionzoft.com
Wednesday, January 11, 2006, 8:53:11 PM, you wrote:
AL> Andrei Zmievski wrote:
As useful functions tend to increase in complexity over time, often so
does the number of parameters.It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last
option.If you get to the point where your function has a dozen parameters, I
would suggest re-thinking the purpose and design of such a function,
because you are likely trying to make it do too much.-Andrei
AL> In a simple highlighting function I wrote (which at 16k hits is probably
AL> considered useful) I needed most of the following parameters:
AL> $text
AL> $needle
AL> $strip_links
AL> $case_sensitive
AL> $whole_word_only
AL> $simple_text_only
AL> $highlight_pattern
AL> $return_or_print
AL> $use_xhtml
AL> $tooltips_or_divs
AL> I imagine any function dealing with html may use a significant portion
AL> of these. Obviously some of these are for effect, but I think my point
AL> is clear enough.
AL> We've discussed other options at developers disposal like associative
AL> arrays, setOpt and getOpt functions in a class, but again each have
AL> their drawbacks and named parameters solve the problem elegantly.
AL> Could we properly discuss the pros and cons of a name parameters
AL> implementation - even if it's only to put the whole issue to bed once
AL> and for all?
AL> Best wishes,
AL> Aidan
Hello Aidan,
I think named parameters would be a useful feature... I'll leave it
at that.Here is a coding idea for you, in case you hadn't considered it...
function highlight($text=NULL, $needle=NULL, $strip_links=NULL, ...)
{
is_null($text) && $text = SOME DEFAULT VALUE;
is_null($needle) && $text = SOME DEFAULT VALUE;
is_null($strip_links) && $text = SOME DEFAULT VALUE;
...
}
Ummmmm, how is that different (ignoring the copy paste bugs in the &&
$text parts) than:
function highlight
(
$text=SOME DEFAULT VALUE,
$needle=SOME DEFAULT VALUE,
$strip_links=SOME DEFAULT VALUE,
...
)
{
...
}
Cheers,
Rob.
.------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com |
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting |
| a powerful, scalable system for accessing system services |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for |
| creating re-usable components quickly and easily. |
`------------------------------------------------------------'
Hello Aidan,
I think named parameters would be a useful feature... I'll leave it
at that.Here is a coding idea for you, in case you hadn't considered it...
function highlight($text=NULL, $needle=NULL, $strip_links=NULL, ...)
{
is_null($text) && $text = SOME DEFAULT VALUE;
is_null($needle) && $text = SOME DEFAULT VALUE;
is_null($strip_links) && $text = SOME DEFAULT VALUE;
...
}Ummmmm, how is that different (ignoring the copy paste bugs in the &&
$text parts) than:function highlight
(
$text=SOME DEFAULT VALUE,
$needle=SOME DEFAULT VALUE,
$strip_links=SOME DEFAULT VALUE,
...
)
{
...
}
To quote Jason, "In [the] way, [that] the user doesn't have to
remember the default values,
just the offsets.".
Michael
To quote Jason, "In [the] way, [that] the user doesn't have to
remember the default values,
just the offsets.".
slaps self Duh :)
Cheers,
Rob.
.------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com |
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting |
| a powerful, scalable system for accessing system services |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for |
| creating re-usable components quickly and easily. |
`------------------------------------------------------------'
Jason Garber wrote:
Here is a coding idea for you, in case you hadn't considered it...
function highlight($text=NULL, $needle=NULL, $strip_links=NULL, ...)
{
is_null($text) && $text = SOME DEFAULT VALUE;
is_null($needle) && $text = SOME DEFAULT VALUE;
is_null($strip_links) && $text = SOME DEFAULT VALUE;
...
}
We use
function highlight($p = array())
{
$p += array( # Also serves as documentation
'text' => SOME_DEFAULT_VALUE,
'needle' => SOME_DEFAULT_VALUE,
'strip_links' => SOME_DEFAULT_VALUE,
...
);
}
...
$highlight(array('strip_links' => true));
in cases just like this.
<shameless_plug>
Plus the patch from http://cschneid.com/php to get
$highlight('strip_links' => true);
</shameless_plug>
If named parameters for PHP are considered in the future then my main
wish would be that there is a catch-all array receiving all the
non-assignable parameters.
- Chris
Andrei Zmievski wrote:
If you get to the point where your function has a dozen parameters, I
would suggest re-thinking the purpose and design of such a function,
because you are likely trying to make it do too much.
Obviously for most methods you should not require more than say 5
parameters. But there are the extremes .. say a query builder and you
dont want to use a fluent interface ;-)
Sometimes you can come up with a very concise method that proxies calls
to other methods and therefore needs quite a ton of (often optional)
parameters. Obviously you can use arrays and things like that to not
force the user to remember the exact parameter order, but it means
adding alot of code for managing defaults and incorrect parameters.
regards,
Lukas
Aidan Lister wrote:
As useful functions tend to increase in complexity over time, often so
does the number of parameters.It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last
option.Sure, you can fall back to associative array parsing. However, I feel it
lacks the rigor that named parameters can give. Named parameters also
give a clean method for the user to see the available options, rather
than reading through source code.
What exactly do you find lack about associative arrays?
Ilia
Aidan Lister wrote:
As useful functions tend to increase in complexity over time,
often so
does the number of parameters.It soon gets to the point where function calls look like:
foo(true, false, false, false, false, true)
The rest of the parameters being required to be supplied, with their
default value, when the user is only interested in changing the last
option.Sure, you can fall back to associative array parsing. However, I
feel it
lacks the rigor that named parameters can give. Named parameters also
give a clean method for the user to see the available options, rather
than reading through source code.What exactly do you find lack about associative arrays?
To put the shoe on the other foot, what exactly do you find lacking
about named parameters so that you'd prefer to use the more
syntactically complex and less sophisticated array method? Quite
frankly, implementing named parameters is sort of a no-brainer; I
understand a reluctance to implement it based on time/effort
considerations, but for some of the core devs to actually defend not
implementing it based on a design decision is weird.
Why named parameters? Because like with normal parameters/arguments,
you must specify required parameters. An associative array is not
enforced by the language -- you have to manually check that the array
has the required parameters and manually throw an error/exception.
That's...stupid. Plus, with the array there is no language-based
documentation for the parameters -- all that the function/method
signature specifies is just one array parameter. That's also stupid.
PHP is all about using a simple means to an end and getting the job
done. Named parameters makes coding easier, not harder. So why defend
keeping it out of the language?
Regards,
Jared
Hello Jared,
JW> PHP is all about using a simple means to an end and getting the job
JW> done. Named parameters makes coding easier, not harder.
Well stated.
--
Best regards,
Jason mailto:jason@ionzoft.com
In my opinion, as Ilia stated passing an associative array does the
job quite well for the use-case where named arguments would be useful.
Sure it might be a tad-bit sexier that you don't have to write
array() but the truth is that the implementation would probably still
use an array. Unlike Ada which has extremely strict typing, in PHP in
most cases we wouldn't be able to optimize away the named parameters,
meaning that we'd probably do the array() trick anyway.
Andi
Hello Andi,
I think the "sexy" syntax is a significant plus, even if associative
arrays were used in the implementation. Is it a complex thing to
implement?
--
Best regards,
Jason mailto:jason@ionzoft.com
Thursday, January 12, 2006, 6:44:59 PM, you wrote:
AG> In my opinion, as Ilia stated passing an associative array does the
AG> job quite well for the use-case where named arguments would be useful.
AG> Sure it might be a tad-bit sexier that you don't have to write
AG> array() but the truth is that the implementation would probably still
AG> use an array. Unlike Ada which has extremely strict typing, in PHP in
AG> most cases we wouldn't be able to optimize away the named parameters,
AG> meaning that we'd probably do the array() trick anyway.
AG> Andi
Andi Gutmans wrote:
In my opinion, as Ilia stated passing an associative array does the job
quite well for the use-case where named arguments would be useful.
Sure it might be a tad-bit sexier that you don't have to write array()
but the truth is that the implementation would probably still use an
array. Unlike Ada which has extremely strict typing, in PHP in most
cases we wouldn't be able to optimize away the named parameters, meaning
that we'd probably do the array() trick anyway.
You are argueing from a php internal level. Named parameters are useful
for situations where you have alot of parameters. I think people have
shown that this may not be the common case, but its still very much real.
People have shown ways to handle default values fairly efficiently.
However this still dances around the language level documentation.
It also dances around the need for error handling entirely. Of course
you could also hack in some checks using array_diff()
to determine if
there are any unwanted parameters and then trigger an error.
Now we have not even addressed the potential for type hinted parameters.
However this means adding a fair amount of LOC, that are much less
obvious to read. Performance in this case is not the main factor, but if
oyu add in a call to array_diff()
with a !empty() if statement I think
its hard to argue that the performance would be equal either.
Also contrary to alot of the things we have added since php 5.x I think
this language feature would be much more obvious and easy to grasp even
without reading any documentation on it. As such it very much fits the
PHP style and has very little risk of obfuscating the language.
Now obviously there would have to be someone to implement it, but I see
no "design" reason to not allow this feature in.
regards,
Lukas
Now obviously there would have to be someone to implement it, but I see no
"design" reason to not allow this feature in.
But I see no reason to add it either...
regards,
Derick
Let me summarize it for you then.
Advantages of named parameters over associative arrays:
- cleaner syntax
- support for type hints
- difference between required and optional parameters
- generating documentation (whether with something like phpDoc or an IDE)
- ...
Can anyone summarize the disadvantages now please?
- Ron
"Derick Rethans" derick@php.net schreef in bericht
news:Pine.LNX.4.62.0601130914440.19056@localhost...
Now obviously there would have to be someone to implement it, but I see
no
"design" reason to not allow this feature in.But I see no reason to add it either...
regards,
Derick
Ron Korving wrote:
Let me summarize it for you then.
Advantages of named parameters over associative arrays:
- cleaner syntax
- support for type hints
- difference between required and optional parameters
- generating documentation (whether with something like phpDoc or an IDE)
- ...
Can anyone summarize the disadvantages now please?
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at all
--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
That's a good point. But for PHP6, wouldn't everything have to be revised
anyway? Another option is to make named parameter support optional per
function. If a user calls a function with named parameters which the
function doesn't support, the engine can trigger an error. This way internal
functions and extensions can be upgraded with named parameter support as
time goes on.
- Ron
"Hartmut Holzgraefe" hartmut@mysql.com schreef in bericht
news:43C786E5.1020400@mysql.com...
Ron Korving wrote:
Let me summarize it for you then.
Advantages of named parameters over associative arrays:
- cleaner syntax
- support for type hints
- difference between required and optional parameters
- generating documentation (whether with something like phpDoc or an IDE)
- ...
Can anyone summarize the disadvantages now please?
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at all--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
That's a good point. But for PHP6, wouldn't everything have to be revised
anyway? Another option is to make named parameter support optional per
function. If a user calls a function with named parameters which the
function doesn't support, the engine can trigger an error. This way internal
functions and extensions can be upgraded with named parameter support as
time goes on.
What a horror.
-1000000000 billions.
P.S. Or are you kidding?
--
Wbr,
Antony Dovgal
Hartmut Holzgraefe wrote:
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at all
I was thinking that this would a userland only feature.
regards,
Lukas
Lukas Smith wrote:
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at allI was thinking that this would a userland only feature.
do we really want to add even more inconsistencies to the language?
--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
Hartmut Holzgraefe wrote:
Lukas Smith wrote:
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at allI was thinking that this would a userland only feature.
do we really want to add even more inconsistencies to the language?
Its a choice you make when you define your signature and you always need
to check the signature before you call a function using named parameters
to know the names of the parameters.
Adding this to functions that do not fall into the category of having 5+
parameters, especially internal ones, would indeed be a horror scenario.
I would therefore even suggest to make it a binary choice. As in the
function does either named parameters or by order.
Its sole purpose is to deal with situations where you have a
considerable number of parameters. I am not aware of internal functions
that fit this criteria. I am not sure if we need to forbid internal
functions to use named parameters (as long as its a binary choice). But
if we keep it binary I do not see it adding confusion. Its certainly
less confusing than having to use some array format that is hard to
document properly.
regards,
Lukas
Lukas Smith wrote:
Its sole purpose is to deal with situations where you have a
considerable number of parameters.
well, i for one would love to write something like
$pos = strpos(haystack=$str, needle="foobar");
instead of looking up parameter orders all the time :)
--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
Hartmut Holzgraefe wrote:
Lukas Smith wrote:
Its sole purpose is to deal with situations where you have a
considerable number of parameters.well, i for one would love to write something like
$pos = strpos(haystack=$str, needle="foobar");
instead of looking up parameter orders all the time :)
I would specifically not go there. This would create the inconsistant
situation you describe. It would be fixing one past mistake with a new evil.
As noted the cases are not as wide as most people make it sound, also
its not really related to this discussion.
regards,
Lukas
I think everybody should be open to a new way of dealing with functions. The
advantages apply to many many functions. Take for example:
mysqli mysqli_connect ( [string host [, string username [, string passwd [,
string dbname [, int port [, string socket]]]]]] )
It would be nice to be able to do
$conn = mysqli_connect(host: $host, port: $port);
without having to worry about anything else than the parameters I care
about.
It's a new way of doing things, and that may be scary, but think how useful
this can be for programmers. When you call a function, the order in which
you present the function parameters is never interesting, except for a few
rare cases like printf()
. But unlike printf()
, the functioning of a strpos()
function doesn't require a certain order in parameters. It requires a needle
and a haystack.
In any situation, including function parameters, I consider requiring a
certain order where it's not needed an overspecification. Just like this is
an overspecification:
for ($i=0; $i < count($array); $i++)
echo $array[$i];
compared to:
foreach ($array as $element)
echo $element;
because you simply don't need $i.
Named parameters are, like foreach, a means to reduce overspecification.
- Ron
"Lukas Smith" lsmith@php.net schreef in bericht
news:43C79EE0.909@php.net...
Hartmut Holzgraefe wrote:
Lukas Smith wrote:
Its sole purpose is to deal with situations where you have a
considerable number of parameters.well, i for one would love to write something like
$pos = strpos(haystack=$str, needle="foobar");
instead of looking up parameter orders all the time :)
I would specifically not go there. This would create the inconsistant
situation you describe. It would be fixing one past mistake with a new
evil.As noted the cases are not as wide as most people make it sound, also its
not really related to this discussion.regards,
Lukas
Ron Korving wrote:
mysqli mysqli_connect ( [string host [, string username [, string passwd [,
string dbname [, int port [, string socket]]]]]] )
coughPDOcough (
http://us3.php.net/manual/en/ref.pdo-mysql.connection.php )
David Hall
I think everybody should be open to a new way of dealing with functions. The
advantages apply to many many functions. Take for example:mysqli mysqli_connect ( [string host [, string username [, string passwd [,
string dbname [, int port [, string socket]]]]]] )It would be nice to be able to do
$conn = mysqli_connect(host: $host, port: $port);
without having to worry about anything else than the parameters I care
about.
You do know that that means that we have to consistently name all
parameters to our 4000+ functions, right? Besides that road block, I
don't see how:
mysqli_connect(host: $host, port: $port);
differs from:
mysqli_connect( array( 'host' => $host, 'port' => $port ) );
(except that it's a bit more to type).
If you're designing an API of your own you can easily design it in such
a way that you don't have that many parameters anyway. A specific class
accepting a lot of parameters can easily set them as default:
<?php
class ezcTranslationTsBackend
{
private $tsLocationPath;
private $tsFilenameFormat = '[LOCALE].xml';
function __construct( $location, array $options = array() )
{
$this->setOptions( array( 'location' => $location ) );
$this->setOptions( $options );
}
public function setOptions( array $configurationData )
{
foreach ( $configurationData as $name => $value )
{
switch ( $name )
{
case 'location':
if ( $value[strlen( $value ) - 1] != '/' )
{
$value .= '/';
}
$this->tsLocationPath = $value;
break;
case 'format':
$this->tsFilenameFormat = $value;
break;
default:
throw new ezcBaseSettingNotFoundException( $name );
}
}
}
?>
You can even easily verify the parameters that you're passing for ranges
etc. This is a cleaner API as it's easier to read, and definitely not
harder to write. On top of that you get the benefit of value/range
checking. The usage is then simply:
<?php
$a = new ezcTranslationTsBackend( 'files' );
?>
or:
<?php
$a = new ezcTranslationTsBackend( 'files', array( 'format' => "test-[LOCALE].xml' ) );
?>
or:
<?php
$a = new ezcTranslationTsBackend( 'files' );
$a->setOptions( array( 'format' => "test-[LOCALE].xml' ) );
?>
It's a new way of doing things, and that may be scary, but think how
useful this can be for programmers. When you call a function, the
order in which you present the function parameters is never
interesting, except for a few rare cases likeprintf()
. But unlike
printf()
, the functioning of astrpos()
function doesn't require a
certain order in parameters. It requires a needle and a haystack.
I would rather think it's less obvious about what is going on. You
should always care in which order you pass arguments to normal
functions, as otherwise you're getting inconsistencies in its usage all
through your application. And I would not be happy to see:
$blah = strpos( haystack: $string; needle: 'F' );
instead of:
$blah = strpos( $string, 'F' );
regards,
Derick
--
Derick Rethans
http://derickrethans.nl | http://ez.no | http://xdebug.org
Derick Rethans wrote:
You do know that that means that we have to consistently name all
parameters to our 4000+ functions, right?
On this note, and to throw in my 2c on the issue (from a doc
standpoint): there are places in the manual where I've (personally)
deliberately changed the parameter names that the developer chose, to
make more sense in the docs. (I don't remember exactly where I did this,
but I suspect it was in classkit or apc.)
An example:
(C):
PHP_FUNCTION(some_file_function) {
...
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &strfn,
&strfn_len) == FAILURE)
...
(docs):
mixed some_file_function( string $filename )
...
"fn" might make sense in C, but not in the docs (where it should be the
more verbose "filename"). So, each function would need to not only
standardize (as Derick mentioned)--having to lookup "fn" vs "filename"
defeats the purpose of named parameters--but the docs would need to be
synced for each function, too.
While the thought of never remembering the parameter order again makes
my mouth (mind?) water, I don't see how it could happen.
As for userspace, a suitable framework could enforce this as associative
arrays, with little overhead on the coding/execution fronts (especially
juicy are the possibilities that have become available with Reflection).
S
mysqli_connect( array( 'host' => $host, 'port' => $port ) );
(except that it's a bit more to type).
Just a small suggestion - what do you all think of creating an array
implicitely on function calls like db_connect('host' => $host, 'port'
=>$port), or funcname($param1, $param2, 'foo' => 'bar'). Those parts
would have to be on the very end of the argument list. Would eliminate
the need for "a bit more to type". function definition would be like
function funcname ($p1, $p2, $params = array());
As I said, just a quick suggestion...
Regards,
Stefan Walk
Stefan Walk wrote:
Just a small suggestion - what do you all think of creating an array
implicitely on function calls like db_connect('host' => $host, 'port'
=>$port), or funcname($param1, $param2, 'foo' => 'bar'). Those parts
would have to be on the very end of the argument list. Would eliminate
the need for "a bit more to type". function definition would be like
function funcname ($p1, $p2, $params = array());
I don't like the array. However, I do like the way you're specifying the
parameter with 'host' and 'port'.
Perhaps something like:
mysqli_connect('host' = $host, 'port' = $port);
:)
Bart
Bart de Boer wrote:
Stefan Walk wrote:
Just a small suggestion - what do you all think of creating an array
implicitely on function calls like db_connect('host' => $host, 'port'
=>$port), or funcname($param1, $param2, 'foo' => 'bar'). Those parts
would have to be on the very end of the argument list. Would eliminate
the need for "a bit more to type". function definition would be like
function funcname ($p1, $p2, $params = array());I don't like the array. However, I do like the way you're specifying the
parameter with 'host' and 'port'.Perhaps something like:
mysqli_connect('host' = $host, 'port' = $port);
:)
Bart
Argh, that was a bad idea. This would mean we could also do:
mysqli_connect($host = $myhost, $port = $myport);
Which currently already is legal syntax.
While ideally it'd be nice to have named parameters used in the core
of PHP, I realize that's probably an impossible task at the moment.
So I agree that the main goal is to allow users to define APIs in PHP
using this feature. If that's all we had, it'd be good enough I
think. (At least, it'd certainly serve my needs. :) )
Thanks Lukas,
Jared
Hartmut Holzgraefe wrote:
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at allI was thinking that this would a userland only feature.
regards,
Lukas
Guys,
It's not going to happen. Please move on. We've discussed it lots of
times in the past. Many times we've come to the conclusion that for a
few cases it's not worth it.
If you have functions with lots of parameters (probably 3-4 in a
whole application) then just use array()'s. It's actually not a
mediocre but a pretty decent solution.
Don't mean to be abrupt but we waste so much bandwidth here on things
we've already discussed in the past, and most of the main dev's
clearly aren't in favor.
Andi
This isn't a waste of bandwidth. This is about the future of the language
and about the fact that PHP is missing a crucial feature that several
other languages have had for years and others are working on -- PHP's
competition, in other words.
Please explain to me how using an array is a solution. As I see it, it's
not. It's a hack. It gives you nothing...no code-completion, no error
checking, no built-in documentation -- not even type hinting which was a
nice add-on for PHP 5.
I don't mean to sound antagonistic, but there's only one justification I
can see for not implementing named parameters and that's time. Actually
defending a design decision of rejecting it quite frankly astonishes me.
Jared
Guys,
It's not going to happen. Please move on. We've discussed it lots of
times in the past. Many times we've come to the conclusion that for a
few cases it's not worth it.
If you have functions with lots of parameters (probably 3-4 in a
whole application) then just use array()'s. It's actually not a
mediocre but a pretty decent solution.Don't mean to be abrupt but we waste so much bandwidth here on things
we've already discussed in the past, and most of the main dev's
clearly aren't in favor.Andi
Each programming & scripting language has its strengths and areas of
focus. Just because another language implements a feature, does not mean
the rest should follow suit. What you fail to realize that every feature
adds to the language complexity, making it more difficult to use, harder
to debug and ultimately makes it slower. PHP's biggest strength since
day one was simplicity, to sacrifice that, to allow someone to use
something that has been hammered into their head in their CS class is
beyond silly.
Ilia
Ilia Alshanetsky wrote:
Each programming & scripting language has its strengths and areas of
focus. Just because another language implements a feature, does not mean
the rest should follow suit. What you fail to realize that every feature
adds to the language complexity, making it more difficult to use, harder
to debug and ultimately makes it slower. PHP's biggest strength since
day one was simplicity, to sacrifice that, to allow someone to use
something that has been hammered into their head in their CS class is
beyond silly.
I agree that argueing that other languages have feature xyz and
therefore PHP should also have it is pointless. PHP works quite well
already and its competitive advantage is among other simplicity. So
things need to be weight well. I feel that named parameters would
actually finally be a new feature that actually makes things simpler
compared to the many features recently added. But then again it seems
that the bulk of people who have the power to actively stear PHP
disagree. So I see little reason to continue this discussion.
regards,
Lukas
Lukas Smith wrote:
compared to the many features recently added. But then again it seems
that the bulk of people who have the power to actively stear PHP
disagree. So I see little reason to continue this discussion.
Nice try, but you forgot Quirk's exception ;-)
- Chris
Ilia Alshanetsky wrote:
Each programming & scripting language has its strengths and areas of
focus. Just because another language implements a feature, does not mean
the rest should follow suit. What you fail to realize that every feature
adds to the language complexity, making it more difficult to use, harder
to debug and ultimately makes it slower. PHP's biggest strength since
day one was simplicity, to sacrifice that, to allow someone to use
something that has been hammered into their head in their CS class is
beyond silly.
yeah, this is exactly why over complicated OOP stuff will never be in
PHP. Oh, wait.....
=)
Brian Moon
Phorum Dev Team
Jared White wrote:
While ideally it'd be nice to have named parameters used in the core of
PHP, I realize that's probably an impossible task at the moment. So I
agree that the main goal is to allow users to define APIs in PHP using
this feature. If that's all we had, it'd be good enough I think. (At
least, it'd certainly serve my needs. :) )
So far there is no difference between a user level and an internal
function from a callers point of view, adding such an asymmetry now
really doesn't sound like the right thing to do ...
--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
Hartmut Holzgraefe wrote:
Jared White wrote:
While ideally it'd be nice to have named parameters used in the core
of PHP, I realize that's probably an impossible task at the moment. So
I agree that the main goal is to allow users to define APIs in PHP
using this feature. If that's all we had, it'd be good enough I think.
(At least, it'd certainly serve my needs. :) )So far there is no difference between a user level and an internal
function from a callers point of view, adding such an asymmetry now
really doesn't sound like the right thing to do ...
There is. Internal functions can take optional parameters per reference,
user level functions can not. (see preg_match, for example).
Regards,
Stefan
Hartmut Holzgraefe wrote:
Ron Korving wrote:
Let me summarize it for you then.
Advantages of named parameters over associative arrays:
- cleaner syntax
- support for type hints
- difference between required and optional parameters
- generating documentation (whether with something like phpDoc or an
IDE)- ...
Can anyone summarize the disadvantages now please?
- all internal and PECL functions need to be recoded as the API
right now doesn't know any concept of parameter names at all
Forgive me if I'm wrong, but shouldn't all this be sorted out at the
code parsing phase? For example:
function foo($a = null, $b = 1, $c = 2) {
...
}
foo(c: 25);
The above call to foo would be interpreted by the parser as if all
parameters were provided:
foo(null, 1, 25);
Thus no need to rework internal parameter passing API at all. Perhaps
I'm missing something?
-Brad
Brad Fisher wrote:
Thus no need to rework internal parameter passing API at all. Perhaps
I'm missing something?
you missed that the parameter name information is just not available
for internal functions, the api works by parameter positions only
right now, so at some level you have to add this information for
all the 4,000+ extension funcitons out there ...
--
Hartmut Holzgraefe, Senior Support Engineer .
MySQL AB, www.mysql.com
Hartmut Holzgraefe wrote:
Brad Fisher wrote:
Thus no need to rework internal parameter passing API at all.
Perhaps I'm missing something?you missed that the parameter name information is just not available
for internal functions, the api works by parameter positions only
right now, so at some level you have to add this information for
all the 4,000+ extension funcitons out there ...
Good point! You are correct, I did overlook that and can see it may be
a large task to define that for all built-ins. Sorry for the noise...
-Brad
Hi,
you missed that the parameter name information is just not available
for internal functions, the api works by parameter positions only
right now, so at some level you have to add this information for
all the 4,000+ extension funcitons out there ...
You can use the ARG_INFO stuff to name parameters (like done in SPL or the
Exception base class) so the name "just" needs to be added where wanted.
A benefit from named parameters compared to array based stuff would be that an
IDE might give better completion support.
This doesn't mean I have real need for named parameters and as Andi said we
shouldn't add every feature one might add.
johannes
At 12:08 AM 1/13/2006, Lukas Smith wrote:
Andi Gutmans wrote:
In my opinion, as Ilia stated passing an associative array does the
job quite well for the use-case where named arguments would be useful.
Sure it might be a tad-bit sexier that you don't have to write
array() but the truth is that the implementation would probably
still use an array. Unlike Ada which has extremely strict typing,
in PHP in most cases we wouldn't be able to optimize away the named
parameters, meaning that we'd probably do the array() trick anyway.You are argueing from a php internal level. Named parameters are
useful for situations where you have alot of parameters. I think
people have shown that this may not be the common case, but its
still very much real.
Yeah I know. I did my small share of Ada hacking in the past :)
People have shown ways to handle default values fairly efficiently.
However this still dances around the language level documentation.It also dances around the need for error handling entirely. Of
course you could also hack in some checks usingarray_diff()
to
determine if there are any unwanted parameters and then trigger an error.Now we have not even addressed the potential for type hinted parameters.
However this means adding a fair amount of LOC, that are much less
obvious to read. Performance in this case is not the main factor,
but if oyu add in a call toarray_diff()
with a !empty() if
statement I think its hard to argue that the performance would be equal either.Also contrary to alot of the things we have added since php 5.x I
think this language feature would be much more obvious and easy to
grasp even without reading any documentation on it. As such it very
much fits the PHP style and has very little risk of obfuscating the language.Now obviously there would have to be someone to implement it, but I
see no "design" reason to not allow this feature in.
I agree it wouldn't be hard to grasp but I think having many ways to
do the same thing in a language is not a good thing. Look where it
took Perl. It's not only about having someone to implement that (we
could resolve that easily) but whether we should have it in the
language. You shouldn't implement everything you can.
Again, I truly understand the cases where it's useful but I think
these cases are relatively few and don't warrant such a major change
and going down the route of creating two completely separate calling styles.
Andi