I have noticed a behavior in PHP that makes sense, but I am unsure how to get around it.
I have a long script, something like this
<?php
if ( file_exists("custom_version_of_this_file.php") ) {
require_once "custom_version_of_this_file.php";
exit;
}
// a bunch of code etc
function x () {
// does something
}
?>
Interestingly, the function x() will get registered with the script BEFORE the require_once() and exit are called, and therefore, firing the exit; statement does not prevent functions in the page from registering. Therefore, if I have a function x() in the require_once() file, the script will crash.
Because of the scenario I am attempting (which is, use the custom file if it exists instead of the original file, which will likely be nearly identical but slightly different), I would like to have the functions in the original (calling) file NOT get registered so that they may exist in the custom file.
Anyone know ho开发者_开发技巧w to accomplish this?
Thanks
You could use the function_exists function. http://us.php.net/manual/en/function.function-exists.php
if (!function_exists("x")) {
function x()
{
//function contents
}
}
You can wrap your functions in a class and extend it to add custom versions.
this_file.php
class DefaultScripts {
function x () {
echo "base x";
}
function y() {
echo "base y";
}
}
if(file_exists('custom_version_of_this_file.php'))
require_once('custom_version_of_this_file.php');
else
$scripts = new DefaultScripts();
custom_version_of_this_file.php
class CustomScripts extends DefaultScripts {
function x () {
echo "custom x";
}
}
$scripts = new CustomScripts();
Results if file exists
$scripts->x(); // 'custom x'
$scripts->y(); // 'base y'
and if it doesn't
$scripts->x(); // 'base x'
$scripts->y(); // 'base y'
精彩评论