Thursday, 26 November 2015

PHP include checking mechanism; try..catch alternative

Including outside PHP files into your script is good for code maintenance.

A regular include line looks like this:

include '/location/to/script.php';

If include fails to process or locate the file, it will post an E_WARNING and your script continues. Include does return a true(1) on success and false(0) on failure. Meanwhile, includes sister function, require, will stop your script in its tracks on failure; both do not throw a catchable exception.

Here are 2 simple, and similar, checking mechanism for including files into your PHP scripts and catching the failures for processing:

$check =
(include $_SERVER['DOCUMENT_ROOT'] . '/location/to/script1.php') +
(include $_SERVER['DOCUMENT_ROOT'] . '/location/to/script2.php') +
(include $_SERVER['DOCUMENT_ROOT'] . '/location/to/script3.php');

2. or:
$check = false;
$check += include './location/to/script1.php';
$check += include './location/to/script2.php';
$check += include './location/to/script3.php';

Then for each of the above you can just test $check

if($check != 3){
    //handle what you want to do, throw error etc

You could also wrap the include mechanism in your own function that throws a normal exception and then use the regular try, catch block exception handling in your calling code.

No comments:

Post a Comment