Reputation: 9538
I have
$test = 'SomeClass';
$ins = new $test;
I want to be able to catch the error if the name for $test
doesn't exist.
I'm not sure what type of exception it threw as PHP didn't gave me anything.
Upvotes: 0
Views: 130
Reputation: 1236
first, you must test if $test class exists. http://php.net/manual/en/function.class-exists.php
Upvotes: 0
Reputation: 48897
With PHP 5.3 (or greater), you can catch exceptions thrown from __autoload
function __autoload($name) {
// if class doesn't exist:
throw new Exception("Class $name not found");
// else, load class source
}
$test = 'SomeClass';
try {
$ins = new $test;
} catch (Exception $e) {
}
Upvotes: 0
Reputation: 44386
Such a construction won't let you catch any errors unless you use some error handler. However you can check whether class exists or not using class_exists()
function.
PS. You should use reflection as it is much more verbose and clear. Also it uses exceptions so you can do something like:
try {
$ref = new \ReflectionClass($className);
} catch (\LogicException $le) {
// class probably doesn't exist
}
Upvotes: 0
Reputation: 18295
Use class_exists()
.
Check first like this:
if(class_exists($test)){
$ins = new $test;
}else{
die("Could not load class'" . $test ."'");
}
Upvotes: 5