Trying to dynamically lo开发者_JAVA技巧ad a class:
require_once(PATH_MODULES."/{$module}/{$module}_admin.php");
$admin_class = $module."Admin";
return $admin_class::get_admin($module);
Produces this error on older versions of PHP:
Parse error: syntax error, unexpected
T_PAAMAYIM_NEKUDOTAYIM in
/home/user/public_html/folder/path/admin/filename.php on line 91
How can I change this code to work for older versions of PHP?
The problem as you probably expected, is that you cannot use dynamic class-names in PHP < 5.3. That's why the ::
is unexpected after the variable.
I don't see any way to go around this. You're not allowed to do this:
$admin_class::get_admin($module);
If this part is always the same:
$admin_class = $module."Admin";
return $admin_class::get_admin($module);
You could (and this is a hack!) add these strings to that module with the module name filled in ofcourse. Or make a separate file for that?
So for module "yourModule"
you add to the "/yourModule/yourModule_admin.php"
file these lines:
$admin_class = "yourModuleAdmin";
return yourModuleAdmin::get_admin($module);
Or add a separate file that you call yourModule_admin.olderversions.php
Not too pretty, I agree.
In PHP <5.3 you can use call_user_func
:
return call_user_func(array($admin_class, 'get_admin'), $module);
Answer was pretty simple:
$admin_class = $module."Admin";
$oAdmin = new $admin_class;
return $oAdmin->get_admin($module);
I would say, go with a factory pattern similar to what you have done in your own answer.
One way would be
static class ModuleFactory
{
static public function get($moduleName) {
if(file_exists($moduleName)) {
$module= new $moduleName;
return $module;
}
else {
throw new Exception("Unkown module $moduleName");
}
}
}
Then you do
$fooBar = ModuleFactory::get("foobar");
I don't like string identifiers and try to avoid them when ever possible. So if you already knew all the modules you could do
static class ModuleFactory
{
const FOO = "foo";
const BAR = "bar";
static public function get($moduleName) {
if(file_exists($moduleName . '.php')) {
$module= new $moduleName;
return $module;
}
else {
throw new Exception("Unkown module $moduleName");
}
}
}
And you would then be able to do
$fooBar = ModuleFactory::get(ModuleFactory::FOO);
This would reduce the chance of getting the spelling wrong.
精彩评论