note 104070 deleted from language.oop5.decon by danbrown
| From: | danbrown@php.net | Date: | Mon, 23 May 2011 15:14:45 +0000 |
| Subject: | note 104070 deleted from language.oop5.decon by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179981@lists.php.net to get a copy of this message | ||
Note Submitter: 3dbox dot pl at gmail dot com
----
@phenixdoc at gmail dot com
Your way and inheriting, makes multiple constructors almost language feature ;)
<?php
header('Content-type: text/plain');
abstract class MultipleConstructor {
public function __construct() {
$args = func_get_args();
if (count($args) == 0) {
if (method_exists($this, '__construct_void')) {
$this->__construct_void();
return;
}
}
$constructName = '__construct';
foreach ($args as $arg) {
$constructName .= '_' . gettype($arg);
}
if (method_exists($this, $constructName)) {
call_user_method_array($constructName, $this, $args);
return;
} else {
throw new Exception('Constructor: ' . $constructName . ' not
exist!');
}
}
}
/* ----------------------------------------------------- */
class User extends MultipleConstructor {
private $name;
private $age;
public function __construct_void() {
$this->name = 'Mat';
$this->age = 24;
}
protected function __construct_string($name) {
$this->name = $name;
$this->age = 48;
}
protected function __construct_string_integer($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$mat = new User();
print_r($mat);
$john = new User('John');
print_r($john);
$andrew = new User('Andrew', 96);
print_r($andrew);
?>
-----------------------------------------------
User Object
(
[name:User:private] => Mat
[age:User:private] => 24
)
User Object
(
[name:User:private] => John
[age:User:private] => 48
)
User Object
(
[name:User:private] => Andrew
[age:User:private] => 96
)