note 78583 deleted from function.func-get-args by peehaa
| From: | peehaa@php.net | Date: | Mon, 08 Apr 2019 06:12:06 +0000 |
| Subject: | note 78583 deleted from function.func-get-args by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210552@lists.php.net to get a copy of this message | ||
Note Submitter: tristan dot colombo at laposte dot net
----
In order to use the function 'func_get_args()' to instanciate differents type of objects,
you must use the Reflection API.
By example, we have two different classes and we want to have an unique function (using an unfixed
number of parameters) to create the objects. We create two classes 'a' and 'b'
where constructors accept different numbers of arguments.
Class a (class/a.class.php):
<?php
include_once 'a.class.php';
class b extends a
{
private $param3;
public function __construct($a, $b, $c)
{
$this->param1 = $a;
$this->param2 = $b;
$this->param3 = $c;
}
public function display()
{
echo $this->param1 . ', ' . $this->param2 . ' and ' .
$this->param3 . '!<br />';
}
}
?>
Class b (class/b.class.php):
<?php
class a
{
private $param1;
private $param2;
public function __construct($a, $b)
{
$this->param1 = $a;
$this->param2 = $b;
}
public function display()
{
echo $this->param1 . ' and ' . $this->param2 . '<br />';
}
}
?>
Main program :
<?php
function classFactory()
{
// Retrieve arguments list
$_args = func_get_args();
// Delete the first argument which is the class name
$_className = array_shift($_args);
// Include the requested class
include_once 'class/' . $_className . '.class.php';
// Create Reflection object
// See : http://www.php.net/manual/en/language.oop5.reflection.php
$_reflection = new ReflectionClass($_className);
// Use the Reflection API
return $_reflection->newInstanceArgs($_args);
}
$a = classFactory('a', 'hello', 'world');
$b = classFactory('b', 'that\'s', 'all', 'folks');
$a->display();
$b->display();
?>