动态创建类时PHP类自动加载?
这个简单的例子不起作用,给我:
致命错误:spl_autoload() [function.spl-autoload]:GmailServer 类 无法加载。
define('USERNAME', 'username');
define('PASSWORD', 'password');
$SERVER = 'GmailServer';
spl_autoload_extensions(".php");
spl_autoload_register();
use Service\Mail\GmailServer;
$server = new $SERVER(USERNAME, PASSWORD);
当然,这是有效的:
$server = new GmailServer(USERNAME, PASSWORD);
我错过了什么吗?
编辑:使用反射(但您必须指定完整的命名空间):
$reflector = new \ReflectionClass("Service\\Mail\\$SERVER");
$server = $reflector->newInstance(USERNAME, PASSWORD);
This simple example won't work, gives me:
Fatal error: spl_autoload() [function.spl-autoload]: Class GmailServer
could not be loaded.
define('USERNAME', 'username');
define('PASSWORD', 'password');
$SERVER = 'GmailServer';
spl_autoload_extensions(".php");
spl_autoload_register();
use Service\Mail\GmailServer;
$server = new $SERVER(USERNAME, PASSWORD);
While, of course, this is working:
$server = new GmailServer(USERNAME, PASSWORD);
Am i'm missing something?
EDIT: Working with reflection (but you HAVE to specify the full namespace):
$reflector = new \ReflectionClass("Service\\Mail\\$SERVER");
$server = $reflector->newInstance(USERNAME, PASSWORD);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以运行这个吗?
如果是,则可能与命名空间相关。如果没有,而且,我宁愿这样做而不是使用这个怪癖,使用工厂模式:
Is it possible to run this?
If it does, it might be namespace related. If not, and also, I'd rather do that than using this quirk, use a factory pattern: