Re: Named arguments revisited
| From: | Christian Schneider | Date: | Thu, 01 Dec 2005 14:59:12 +0000 |
| Subject: | Re: Named arguments revisited | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-20951@lists.php.net to get a copy of this message | ||
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) {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 ;-) - Chrisif (!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));