0

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 how to accomplish this?

Thanks

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i considered that, but it is the exact opposite of what I want to accomplish. I want the functions in the custom file to trump the ones in the original -- this solution does the opposite, and since I already know they all exist, I am better off just deleting the functions from the custom file (or renaming them). Thats a workable scenario, but really looking for a way to use custom file without functions from original file. Thanks for the reply though.
You could look in to the runkit library (php.net/manual/en/book.runkit.php). I've never used it but it does have runkit_function_remove and runkit_function_redefine function. You may be able to use it to redefine your methods based on various includes. Seems a little dangerous though.
0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.