Pwnna
Pwnna

Reputation: 9538

PHP class initiation error?

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

Answers (4)

fdaines
fdaines

Reputation: 1236

first, you must test if $test class exists. http://php.net/manual/en/function.class-exists.php

Upvotes: 0

webbiedave
webbiedave

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

Crozin
Crozin

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

Cyclone
Cyclone

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

Related Questions