Re: PHP RFC: Deffering functions by arguments (count or/and type)

From: Date: Tue, 05 Nov 2013 15:28:19 +0000
Subject: Re: PHP RFC: Deffering functions by arguments (count or/and type)
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-70015@lists.php.net to get a copy of this message
Hello there. You can actually do the first part using __call($methodName, array $args). It's a little more complex to do that, but consider that as a current solution. Alternatively, use func_get_args() inside your function, or set the second parameter like method($arg1, $arg2=null) and check if it is, or isn't null using if(is_null($arg2)), and then do what the function should return on either scenario. I know, you are listing these cases within your list of benefits, but one if is less work than having PHP decide which "version" of the function you're wanting to use - I bet it'd make the actual runtime slightly slower. The second part sounds interesting IMHO, but I somehow doubt it'd be accepted. But we'll see. Kind regards, Ingwie Am 05.11.2013 um 14:03 schrieb Oleg Poludnenko <oleg@poludnenko.info>: > Hi, > > My idea is somehow related to this one: Syntax for variadic > functions<https://wiki.php.net/rfc/variadics> > It is not a competitive idea but a supplemental one. > > So, the main point is to write different implementations for the functions > with the same name, but with different of arguments count or/and type: > > class Config { /** * Returns property value * @param string $key * > @returnmixed */ > public function prop($key) { return isset($this->prop[$key]) ? $this->prop[ > $key] : null; } /** * Sets property value * @param string $key * > @parammixed $value *@returnConfig */ > public function prop($key, $value) { $this->prop[$key] = $value; return > $this; } } > > Also it will be possible to change arguments during inheritance: > > class Figure { /** * Calculate perimeter of an arbitrary figure * > @paramarray $angles *@returnint */ > public function calcPerimeter(array $angles) { return array_sum($angles); } > } class Square extends Figure { /** * Calculate perimeter of a square > *@paramint $angle *@returnint */ > public function calcPerimeter($angle) { return 4 * $angle; } } class > Rectangle extends Figure { /** * Calculate perimeter of a rectangle * > @paramint $height *@paramint $width *@returnint */ > public function calcPerimeter($height, $width) { return 2 * ($height + > $width); } } > > The advantages of the syntax are: > > - It's immediately clear what function implements. > - The function becomes cleaner, without a lot of if-else constructions. > - A great opportunity to change function arguments during inheritance. > > > Regards, > Oleg Poludnenko

« previous php.internals (#70015) next »