0

I have a main php file in the root which is included by several others on different directories ,I don't want to allow few functions written in main files to execute if included by another file. I ran an test code and tried overwriting an function by re-declaring it on including but it returned an error:

a.php

<?php
function show(){echo "a";}//This is what I want to over-ride with
include 'b.php';

b.php

<?php
function show(){echo "b";}//This is the function i want to restrict.
show();

Fatal error: Cannot redeclare abc() (previously declared in C:\xampp\htdocs\abc.php:3) in C:\xampp\htdocs\xyz.php on line xx.

4 Answers4

1

You can do this with anonymous functions (PHP5.3)

$show = function(){
    echo "a";
};
$show = function(){
    echo "b";
};
$show();

Will now echo "b".

brasofilo
  • 25,496
  • 15
  • 91
  • 179
dschibait
  • 104
  • 4
0

You can't redeclare a function. You need to use unique names for each function.

The functions won't execute just because you include the file they're in. That is unless you're actively calling them inside the file.

I'd suggest evaluating the way you include files to resolve your issue. You may also want to look into include_once / require_once and the function_exists conditional.

E.g.

if ( ! function_exists( 'my_function' ) ) :

function my_function() {

}

endif;
Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
0

The best way to do this would be to use PHP's OOP features, which allow you to specify visibility of methods.

George Brighton
  • 5,131
  • 9
  • 27
  • 36
0

You can check within a function if the "main file" is included or not, try something like this:

function someFunction() {
    if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
        echo "Not included.";       
    } else {
        echo "Included. No access.";
    }
}

Or place the condition "outside" the function(s) definition, so it won't be defined if you include that file.

But I would go with an OOP approach.