|
Posted by Henk Verhoeven on 10/21/21 11:50
Hi Alexander,
Your message seems somewhat mixed-up. As far as i know the only way to
create a class is to have php interpret a class definition like:
class MyClass extends MySuperclass {
//variables and methods go here
}
As far as i know the following does not work:
$className = 'MyClass';
$superclassName = 'MySuperclass';
class $className extends $superclassName {
//variables and methods go here
}
(please correct me if i am wrong - if this actually would work!)
Furthermore you can call static methods as well as instance methods
using call_user_func_array according to the explanation of the the
callback type:
- Static class methods can also be passed without instantiating an
object of that class by passing the class name instead of an object as
the element with index 0.
- A method of an instantiated object is passed as an array containing an
object as the element with index 0 and a method name as the element with
index 1.
Finally you can do is INSTANTIATE a class dynamicly:
$myClassName = 'MyClass';
$newObject = new $myClassName($param1, $param2);
I agree this does nog allow you to pass the parameters as an array.
Is that what you want?
You ARE allowed to pass more parameters then the constructor of the
class needs. You could write a function like this that will pass a
limited number of parameters from an array:
function instantiate_array($className, $parameters) {
if (count($parameters) > 4)
trigger_error('too many parameters', E_USER_ERROR);
for ($i=0; $i<4; $i++) {
$varName = "p$i";
if (isSet($parameters[$i]);
$$varName = $parameters[$i]
else
$$varName = null;
}
return new $className($p0, $p1, $p2, $p3);
}
I agree this does have an if statement, but at least if you need more
parameters, you do not need to add more if statments.
(Possible disadvantage: the null values that are passed may override
defaults defined in the constructors parameter list)
Greetings,
Henk Verhoeven,
www.phpPeanuts.org.
AlexVN wrote:
> Hi,
>
> I would like to know if someone investigated the method of creating
> classes dynamically depending on the name. I do not like a lot of ifs
> and I suppose that something like call_user_func_array('ClassName',
> array($param1, $param2, $param3, ..., $paramN)) should exist over the
> PHP language. Any suggestions?
>
> Thanks,
> Alexander
> http://www.alexatnet.com/
>
[Back to original message]
|