note 78583 added to function.func-get-args
| From: | tristandotcolomboatlapostedotnet at osu1 dot php dot net | Date: | Thu, 18 Oct 2007 08:03:28 +0000 |
| Subject: | note 78583 added to function.func-get-args | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131484@lists.php.net to get a copy of this message | ||
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();
?>
----
Server IP: 217.174.196.197
Probable Submitter: 217.128.145.133
----
Manual Page -- http://www.php.net/manual/en/function.func-get-args.php
Edit -- https://master.php.net/note/edit/78583
Del: integrated -- https://master.php.net/note/delete/78583/integrated
Del: useless -- https://master.php.net/note/delete/78583/useless
Del: bad code -- https://master.php.net/note/delete/78583/bad+code
Del: spam -- https://master.php.net/note/delete/78583/spam
Del: non-english -- https://master.php.net/note/delete/78583/non-english
Del: in docs -- https://master.php.net/note/delete/78583/in+docs
Del: other reasons-- https://master.php.net/note/delete/78583
Reject -- https://master.php.net/note/reject/78583
Search -- https://master.php.net/manage/user-notes.php