1

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);
8
  • Are you sure GmailServer.php exists in the current folder? Commented Nov 24, 2011 at 22:01
  • Yes, and also new GmailServer one line below will work. Commented Nov 24, 2011 at 22:05
  • 1
    It may be a namespace bug.... have you tried with the qualified class name, or moving GmailServer into a Service/Mail folder? Alternatively, call_user_func might help - with __construct as the function name Commented Nov 24, 2011 at 22:13
  • @PhilLello GmailServer is already in Service/Mail folder, thanks for helping. Commented Nov 24, 2011 at 22:28
  • 1
    I second Phil Lello, I think it's namespace related. When he said "fully qualified name", he meant $SERVER = 'Service\Mail\GmailServer'; Commented Nov 24, 2011 at 22:44

1 Answer 1

1

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);   
        }      
    } 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Of course your first example would work because the lack of namespace. I will use reflection class, but the question is still why it's not working when namespace is defined. Is this a bug?
+1 because I like using factories whenever possible - it makes it so much easier to change implementations in one place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.