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" <[EMAIL PROTECTED]> schreef in bericht
news:[EMAIL PROTECTED]
> 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?
>
>
>
>> On Nov 29, 2005, at 11:17 PM, 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. 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.
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php