note 78460 added to language.oop5.overloading
| From: | egingell at sisna dot com | Date: | Fri, 12 Oct 2007 18:26:52 +0000 |
| Subject: | note 78460 added to language.oop5.overloading | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131351@lists.php.net to get a copy of this message | ||
@ zachary dot craig at goebelmediagroup dot com
I do something like that, too. My way might be even more clunky.
<?php
function sum() {
$args = func_get_args();
if (!count($args)) {
echo 'You have to supply something to the function.';
} elseif (count($args) == 1) {
return $args[0];
} elseif (count($args) == 2) {
if (is_numeric($args[0]) && is_numeric($args[1])) {
return $args[0] + $args[1];
} else {
return $args[0] . $args[1];
}
}
}
?>
I like the "__call" method, though. You can "declare" multiple functions that
don't pollute the namespace. Although, it might be better looking to use this instead of a
series of if...elseif... statemenets.
<?php
class myClass {
function __call($fName, $fArgs) {
switch($fName) {
case 'sum':
if (count ($fArgs) === 1) {
return $fArgs[0];
} else {
$retVal = 0;
foreach( $fArgs as $arg ) {
$retVal += $arg;
}
return $retVal;
}
break;
case 'other_method':
...
default:
die ('<div><b>Fetal Error:</b> unknown method ' . $fName .
' in ' . __CLASS__ . '.</div>');
} // end switch
}
}
?>
Side note: if you don't force lower/upper case, you will have case sensitive method names. E.g.
$myclass->sum() !== $myclass->Sum().
----
Server IP: 69.147.83.197
Probable Submitter: 67.42.120.90
----
Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php
Edit -- https://master.php.net/note/edit/78460
Del: integrated -- https://master.php.net/note/delete/78460/integrated
Del: useless -- https://master.php.net/note/delete/78460/useless
Del: bad code -- https://master.php.net/note/delete/78460/bad+code
Del: spam -- https://master.php.net/note/delete/78460/spam
Del: non-english -- https://master.php.net/note/delete/78460/non-english
Del: in docs -- https://master.php.net/note/delete/78460/in+docs
Del: other reasons-- https://master.php.net/note/delete/78460
Reject -- https://master.php.net/note/reject/78460
Search -- https://master.php.net/manage/user-notes.php