gremo
gremo

Reputation: 48899

PHP class autoloading when creating class dynamically?

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);

Upvotes: 1

Views: 1304

Answers (1)

CodeCaster
CodeCaster

Reputation: 151588

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);   
        }      
    } 
}

Upvotes: 1

Related Questions