simonrs Posted August 18, 2008 Share Posted August 18, 2008 I've been wondering about a few things that other languages have that I don't know how to do in PHP, and searching these forums have found me ways to do most of them in PHP. Which is fantastic, because PHP is about 100x nicer to use than any lower level rubbish and won't force me to spend most of my programming days correctly positioning tabs and spaces *coughpythoncough* So one of the features I haven't discovered a substitute for yet is not so much what might be considered "overloading" in a traditional sense, but more if I want to specify certain arguments to a function without specifying the others. So if I had: class Dog { public function make_noises($woofstr = null, barkstr = null) { echo $woofstr . ', and while I'm at it ' . $barkstr; } } How can I make a call to that method, while only specifying a bark string, without doing, $dog = new Dog(); $dog->make_noises(null, 'BARK BARK BARK!'); Put another way, is there an equivalent to: $dog = new Dog(); $dog->make_noises($bark = 'BARK BARK BARK!'); Link to comment https://forums.phpfreaks.com/topic/120186-specifying-specific-arguments/ Share on other sites More sharing options...
448191 Posted August 18, 2008 Share Posted August 18, 2008 The simplest way to accomplish named arguments is to simply use an associative array as an argument. E.g.: public function foo($spec) { //Validate input $requiredKeys = array('foo', 'bar'); $missingKeys = array_diff_key(array_flip($requiredKeys), $spec); if(count($missingKeys)) { throw new Exception('Missing required keys: ' . implode(', ', $missingKeys)); } } If you don't require named arguments, but rather not commit to a number of arguments, you can use func_get_args(). PHP doesn't complain if you use more arguments than in the method declaration, so something like this works fine (example from my custom base Exception class): /** * Create a new exception. * * You may use a formatted string (using %, as used by printf()) * and add an arbitrary number of arguments to be formatted. * * @param string $message */ public function __construct($message = null) { if($message === null) { $message = $this->messages[self::MSG_DEFAULT]; $this->_setCode(self::MSG_DEFAULT); } elseif(is_int($message)) { $this->_setCode($message); if(! isset($this->messages[$message])) { $message = $this->messages[self::MSG_DEFAULT]; } else { $message = $this->messages[$message]; } } if(func_num_args() > 1) { $this->_messageArgs = func_get_args(); array_shift($this->_messageArgs); $message = $this->parseMessageText($message); } parent::__construct($message); } Link to comment https://forums.phpfreaks.com/topic/120186-specifying-specific-arguments/#findComment-619157 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.