8

I have script wherein basename() is used 100-1000s of time, I was just thinking if we can override the function rather than changing the function name to something else in all scripts.

The problem with basename() is that it doesnt works well with names of files in foreign languages. I found one on php site http://php.net/manual/en/function.override-function.php but it needs PECL any other alternative?

Ross
  • 18,117
  • 7
  • 44
  • 64
Shishant
  • 9,256
  • 15
  • 58
  • 79

3 Answers3

8

You can use namespaces to override existing function names:

namespace blarg;
function basename() {
  return 'whatever';
}
$base = basename();

I.e., any call to basename() within the blarg namespace will use your new version of the function.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • 3
    Remember that namespaces are only supported in PHP 5.3 and later. – BoltClock Oct 13 '10 at 21:11
  • Attempting to otherwise override a function will result in a 'function already exists' error. Lacking 5.3: create a function `xbasename()` that encapsulates the true basename function along with another method for handling non-ansi characters. Then, CTRL-A & CTRL-H... I'm sure everyone knows the rest. – bob-the-destroyer Oct 18 '10 at 20:23
  • sometimes override implementation needs to call original function. In this example is there a way to call the original basename from the new basename ? – Frederic Bazin Jun 22 '11 at 13:23
  • 3
    Prefix the function name with a backslash to indicate that you want the one in the root namespace: \basename(); – Alex Howansky Jun 22 '11 at 13:26
  • Thanks @Alex. I am now trying to use this function in other php files. I first tried 'require_once('overridebasename.php'); use blarg.basename; 'whihc is not working by the way. But anyway this quite a pain if I want to override several functions. Is there a way to inject all overidden function after require_once ? NB: starting with every file with 'namespace blarg; require_once 'overridebasename.php'; do the trick but affect the file's namespace. – Frederic Bazin Jun 23 '11 at 01:47
2

An alternative would be runkit. But that's as unlikely to be enabled on most servers.

mario
  • 144,265
  • 20
  • 237
  • 291
1

You can change the locale before calling basename:

setlocale(LC_ALL, 'en_US.UTF8');

setlocale

webbiedave
  • 48,414
  • 8
  • 88
  • 101