How do I remove the include file?
I have two files included in my page. Like this:
// mypage.php
include 'script1.php';
include 'script2.php';
I need both of them to be first and then I need to remove one of them, something like this:
if ($var == 'one') {
// inactive script1.php file
} else {
// inactive script2.php file
}
It's hard to explain why I need to inactively one of them, I just want to know how can I do this? Is it possible unlike include
?
The simple answer is no, you can't.
The extended answer is that it does two passes when PHP starts up. The first pass compiles PHP to machine code. Is added here include
. The second pass is to execute the code from the first pass. Since the compilation pass is done when include
it was done, there is no way to remove it at runtime.
Since you have a function clash, here's how to get around it with objects (classes)
class Bob {
public static function samename($args) {
}
}
class Fred {
public static function samename($args) {
}
}
Note that both classes have a function samename()
, but they live in a different class, so there is no collision. Since they are static
, you can call them that
Bob::samename($somearghere); Fred::samename($somearghere);
source to share
Like your comments, you said that due to the duplicate function names, I am assuming that you are using both files in a different location separately, but what you are trying to achieve is to combine these files for a different reason (both file have functions / variables etc. that you need)
If your first file had a my_function like this:
my_function() {
// code here
}
and your second file also had the same named function, you can wrap it with an if to exclude it:
if (!function_exists('my_function')) {
my_function() {
// code here
}
}
Thus, the second function of the file will not be available when merging the two files together, but using the file separately, both functions will be available.
source to share
In order to provide options for others who come here, some of the solutions I've used on my own ...
- If you include files, you include a return value or some execution for some function that does not need to be displayed on the page (for example, a mailing list), and, say, you cannot change any of the target files (let's say they are foreign code or piece of some highly integrated software that you really don't want to untangle).
The solution is to create a quick and dirty interface to rest both files, to extract what you want from them, and then invoke that interface with your program, effectively bypassing the need to include them.
Worse method, but if your situation is really desperate and really is a last resort, and will only work in some cases (for example, violate the namespace) ...
$ bad_idea = file_get_contents ("foo.php");
Eval ($ bad_idea);
disarmed ($ bad_idea);
Again, please note this is a last resort option.
source to share