user3832591
user3832591

Reputation:

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!

Upvotes: 2

Views: 254

Answers (2)

Greg K
Greg K

Reputation: 434

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:

Upvotes: 3

Álvaro González
Álvaro González

Reputation: 146390

As far as I know, function disabling in PHP is an all or nothing setting:

  • You can make the extension not load at all.
  • You can ban the function with disable_functions, which is PHP_INI_SYSTEM thus a system-wide setting.

I don't think there's nothing as fine-grained as you ask. Whatever reason you have to write new code with the legacy mysql extension, you'll have to find another solution.

Upvotes: 1

Related Questions