动态创建类时PHP类自动加载?

发布于 2024-12-18 04:54:14 字数 677 浏览 2 评论 0原文

这个简单的例子不起作用,给我:

致命错误: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉梦枕江山 2024-12-25 04:54:14

可以运行这个吗?

class Foo { }
$c = "Foo";
$f = new $c();

如果是,则可能与命名空间相关。如果没有,而且,我宁愿这样做而不是使用这个怪癖,使用工厂模式:

static class ServerFactory 
{
    public static function GetServer($server, $username, $password)
    {
         switch ($server)
        {
            case "GmailServer": return new GmailServer($username, $password);   
        }      
    } 
}

Is it possible to run this?

class Foo { }
$c = "Foo";
$f = new $c();

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:

static class ServerFactory 
{
    public static function GetServer($server, $username, $password)
    {
         switch ($server)
        {
            case "GmailServer": return new GmailServer($username, $password);   
        }      
    } 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文