i have this code :
JavaScript
x
<?PHP
function call_and_set( $obj, $txt){
return call_user_method('example', $obj, $txt);
}
class test{
function example($text){
echo $text;
}
}
$test = new test();
call_and_set($test, "Hello World!");
?>
in my code i don’t always want to use
$test = new test ….
I want to use the name directly instead of $test
. For example:
JavaScript
call_and_set("test", "Hellow World!").
Advertisement
Answer
You should use a factory method pattern or something like that. With a factory method you can create a class based on a string. In PHP it’s not that hard. Try something like this:
JavaScript
<?PHP
function call_and_set( $className, $txt) {
$obj = ProductFactory::create($className);
return call_user_method('example', $obj, $txt);
}
class test
{
function example($text){
echo $text;
}
}
class ProductFactory
{
public static function create($className) {
//Add some checks and/or include class files
return new $className();
}
}
call_and_set("test", "Hello World!");
?>