Multiple constructors in php
The easiest way to use and understand multiple constructors:
class A
{
function __construct()
{
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f=’__construct’.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct1($a1)
{
echo(‘__construct with 1 param called: ‘.$a1.PHP_EOL);
}
function __construct2($a1,$a2)
{
echo(‘__construct with 2 params called: ‘.$a1.’,’.$a2.PHP_EOL);
}
function __construct3($a1,$a2,$a3)
{
echo(‘__construct with 3 params called: ‘.$a1.’,’.$a2.’,’.$a3.PHP_EOL);
}
}
$o = new A(‘name’);
$o = new A(‘name’,’book’);
$o = new A(‘name’,’book’,’author’);
// results:
// __construct with 1 param called: name
// __construct with 2 params called: name,book
// __construct with 3 params called: name,book,author
Another way to imulate multiple constructors:
<?php
class MyClass {
// use a unique id for each derived constructor,
// and use a null reference to an array,
// for optional parameters
function __construct($id=””, $args=null) {
// parent constructor called first ALWAYS
parent::__construct();
echo “main constructor\n”;
// avoid null or other types
$id = (string) $id;
// allow default constructor
if ($id == “”) {
$id = “default”;
}
// just in case, use lowercase id
$id = “__cons_” . strtolower($id);
$rc = new ReflectionClass(“MyClass”);
if (!$rc->hasMethod($id) {
echo “constructor $id not defined\n”;
}
else {
// using “method references”
$this->$id($args);
}
$rc = null;
} // function __construct
// ALWAYS HAVE A default constructor,
// that ignores arguments
function __cons_default($args=null) {
echo “Default constructor\n”;
}
// may have other constructors that expect different
// argument types or argument count
function __cons_min($args=null) {
if (! is_array($args) || count($args) != 2) {
echo “Error: Not enough parameters (Constructor min(int $a, int $b)) !!!\n”;
}
else {
$a = (int) $args[0];
$b = (int) $args[1];
$c = min($a,$b);
echo “Constructor min(): Result = $c\n”;
}
}
// may use string index (associative array),
// instead of integer index (standard array)
function __cons_fullname($args=null) {
if (! is_array($args) || count($args) < 2) {
echo “Error: Not enough parameters (Constructor fullname(string $firstname, string $lastname)) !!!\n”;
}
else {
$a = (string) $args[“firstname”];
$b = (string) $args[“lastname”];
$c = $a . ” ” . $b;
echo “Constructor fullname(): Result = $c\n”;
}
}
} // class
// –> these two lines are the equivalent
$obj1 = new TestClass();
$obj2 = new TestClass(“default”);
// –> these two are specialized
// should be read as “$obj3 = new TestClass, min(99.7, 99.83);”
$obj3 = new TestClass(“min”, array(99.7, 99.83));
// should be read as “$obj4 = new TestClass, fullname(“tesk”, “name”);”
$obj4 = new TestClass(“fullname”, array(“firstname” => “test”, “lastname” => “name”));
// –> these two lack parameters
$obj5 = new TestClass(“min”, array());
$obj6 = new TestClass(“fullname”);
?>