First of all, I don't think using autoload is recommended.

If you really want to do it that way, you could check if the file which autoload will try to include exists and if it does, include it and create your object.

Actually to make the script more safe, after including the file you should check if the class exists (because the file might exist but not have the class in it) and only then you can make the object of that class.

I suppose you could throw the exception you want and do it with the try-catch as you like it :)

Sorry if my English is bad and if didn't get what you want to do.

"Larry Garfield" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
Greetings, all.

I am trying to figure out a way to implement the following logic, but I am not
sure if it is possible to do so without a lot of additional side work:

I have a class, A, and another class B that extends A. They live in separate
files.  The logic I need to implement is as follows:

if (class_exists('B')) {
 $foo = new B();
}
else {
 $foo = new A();
}

That is all well and good if both A and B are already loaded and parsed, but I
am using spl_autoload to lazy-load classes as needed.  That means the
class_exists() call will return false if B exists but hasn't been included
yet.  What I would like to happen is for PHP to include B if it exists or
give a non-fatal error if it doesn't so that I can instantiate A instead.

Ideally, the logic would be something like the following:

try {
 $foo = new B();  // Try to autoload B, throw exception if it can't.
}
catch (ClassDoesntExistEvenAfterRunningThroughAutoloadException $e) {
 $foo = new A(); // May autoload A at this point, too.
}
// do stuff with $foo

However, as far as I am aware $foo = new B(); will cause a fatal exception if
autoload doesn't find a B.

Does anyone know of a way to achieve the above effect? This is specifically
for PHP 5.2 and later.  Thanks.

--
Larry Garfield
[EMAIL PROTECTED]


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to