Search code examples
phpfunctionclasscallrestrict

php Restricting function call to certain class


I have a class named db.php..... and I have the following method in it.

function query($sql){
   return mysql_query($sql);
}

I want that only this class can use

mysql_query

but others can't. And others can only use by calling the

$db->query

function of this class.

Is it possible? Any help would be greatly appreciated!


Solution

  • I am pretty sure this can be achieved in an indirect way. You can rename the function and then call it again if you want:

    rename_function('mysql_query', 'mysql_query_old' );
    
    function mysql_query(){
      //do whatever
      //pass the call to original method if needed.
      $args = func_get_args();
      if (count($args) === 2)
        return mysql_query_old($args[0], $args[1]);
      else
        return mysql_query_old($args[0]);
    }
    

    To restrict it to a certain class only, you could just check the calling class:

    $trace = debug_backtrace()[1];
    $class = $trace['class'];
    

    Take a look here and here for more info: