I am in a situations where i need to instantiate a class with arguments from within an instance of another class. Here is the prototype:
//test.php
class test
{
function __construct($a, $b, $c)
{
echo $a . '<br />';
echo $b . '<br />';
echo $c . '<br />';
}
}
Now, i need to instantiate above class using below class's cls function:
class myclass
{
function cls($file_name, $args = array())
{
include $file_name . ".php";
if (isset($args))
{
// this is where the problem might be, i need to pass as many arguments as test class has.
$class_instance = new $file_name($args);
}
else
{
$class_instance = new $file_name();
}
return $class_instance;
}
}
Now when i try to create an instance of test class while passing arguments to it:
$myclass = new myclass;
$test = $myclass->cls('test', array('a1', 'b2', 'c3'));
It gives error: Missing argument 1 and 2; only first argument is passed.
This works fine if i instantiate a class which has no arguments in it's constructor function.
For experienced PHP developers, above should not be much of a problem. Please help.
Thanks
We're in 2019 now and we have php7 now... and we have the spread-operator (...) . We can now simply call
you need Reflection http://php.net/manual/en/class.reflectionclass.php
You can:
1) Modify test class to accept an array, which contains the data you wish to pass.
2) initiate using a user method instead of the constructor and call it using the
call_user_func_array()
function.In your main class:
http://www.php.net/manual/en/function.call-user-func-array.php
Lastly, you can leave your constructor params blank and use
func_get_args()
.http://sg.php.net/manual/en/function.func-get-args.php
The easiest way I have found:
Sorry a bit raw, but you should understand the idea.
You could use call_user_func_array() I believe.
or you could leave the arguments list of the constructor, and then inside the constructor use this
$object = new textProperty($start, $end);
don't work?