views:

39

answers:

3

Hello all, To throw an exception we need to include a CustomException class.

include_once("CustomException.class.php");

Ok.

On another file, when we use the try/catch blocks, do we need to require or include, our CustomException class again?

Thanks in advance, MEM

+2  A: 

No, you do not need to re-include it in the try/catch blocks. Once a file is included it should be valid / available for the entire processing of the script.

Brad F Jacobs
I think you missed the point. You only need to require the exception class if you throw that exception. So what I read the OP to be asking is if (s)he needs to include the class simply for the type hint in the catch block to work... (kind of how `$obj = new Foo()` will fatal error if the `Foo` class is not defined)...
ircmaxell
Gotcha, I probably did miss it. Thanks for elaborating.
Brad F Jacobs
+1  A: 

If I understand what you're trying to do correctly, then no, because when you include the file that has the class that throws CustomException, it will include the CustomException class already.


Consider the following situation, where we have a main file which includes a file (which includes a file itself):

main.php:

include("include1.php");
var_dump($variable_defined_in_include2);

include1.php:

include("include2.php");

include2.php:

$variable_defined_in_include2 = true;

Even though main.php doesn't include include2.php, $variable_defined_in_include2 will be set because include1.php is included, which includes include2.php.

Daniel Vandersluis
+3  A: 

If the exception of this class was thrown, it has already been included at this point of the script. And if it's not thrown nothing bad happens. The typehint will not raise any errors if there's no such exception defined. Try running this code:

try {
 echo 'foo';
} catch (SomeNonExistentException $e) {
 echo 'bar';
}
echo 'baz';
Mchl
Exactly. Type hints never require the class to exist. It will only pass the hint of the object passes an `$obj instanceof FooClass`, but `FooClass` is never required to exist (from the parser's standpoint)...
ircmaxell
Thanks. With this extra comment now I get it. It seems to be related with type hints. And that was a key term. thanks a lot
MEM