note 113968 added to language.oop5.decon
| From: | Anonymous | Date: | Mon, 23 Dec 2013 13:45:58 +0000 |
| Subject: | note 113968 added to language.oop5.decon | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198010@lists.php.net to get a copy of this message | ||
By inheriting from this class, you can do constructor overloading in terms of type hinting.
<?php
abstract class OverloadedConstructors {
public final function __construct() {
$self = new ReflectionClass($this);
$constructors = array_filter($self->getMethods(ReflectionMethod::IS_PUBLIC),
function(ReflectionMethod $m) {
return substr($m->name, 0, 11) === '__construct';
});
if(sizeof($constructors) === 0)
trigger_error('The class ' . get_called_class() . ' does not provide a
valid constructor.', E_USER_ERROR);
$number = func_num_args();
$arguments = func_get_args();
foreach($constructors as $constructor) {
if(($number >= $constructor->getNumberOfRequiredParameters()) &&
($number <= $constructor->getNumberOfParameters())) {
$parameters = $constructor->getParameters();
reset($parameters);
foreach($arguments as $arg) {
$parameter = current($parameters);
if($parameter->isArray()) {
if(!is_array($arg))
continue 2;
}elseif(($expectedClass = $parameter->getClass()) !== null) {
if(!(is_object($arg) && $expectedClass->isInstance($arg)))
continue 2;
}
next($parameters);
}
$constructor->invokeArgs($this, $arguments);
return;
}
}
trigger_error('The required constructor for the class ' . get_called_class() .
' did not exist.', E_USER_ERROR);
}
}
?>
Simply define a class like this:
<?php
class Test extends OverloadedConstructors {
public function __construct1(array $arg) {
die('First construct');
}
public function __construct2(stdClass $test) {
die('Second construct');
}
public function __construct3($optional = null) {
die('Third construct');
}
}
?>
You can define as much constructors as you wish and limit them by php's type hinting. Note that
the constructor signatures should be non-ambiguous.
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/language.oop5.decon.php
Edit -- https://master.php.net/note/edit/113968
Del: integrated -- https://master.php.net/note/delete/113968/integrated
Del: useless -- https://master.php.net/note/delete/113968/useless
Del: bad code -- https://master.php.net/note/delete/113968/bad+code
Del: spam -- https://master.php.net/note/delete/113968/spam
Del: non-english -- https://master.php.net/note/delete/113968/non-english
Del: in docs -- https://master.php.net/note/delete/113968/in+docs
Del: other reasons-- https://master.php.net/note/delete/113968
Reject -- https://master.php.net/note/reject/113968
Search -- https://master.php.net/manage/user-notes.php