Tutorial :Function name conflict in php from 2 different libraries



Question:

I have 2 'libraries' which I need to include on the same page. Simple Machine Forums and Wordpress.

However both have the function is_admin() which conflicts with each other.

Fatal error: Cannot redeclare is_admin() (previously declared  in /home/site.com/wordpress/wp-includes/query.php:100)in /home/site.com/smf/Sources/Security.php on line 82)  

What would be the best way to get around this? As I dont want to have to modify all calls to one library to be is_admin2() for example.


Solution:1

I believe you don't have too much choice but to rename the function or, wrap all functions around a class. That's the problem with PHP <= 5.*: no namespaces, and developers often prefer to write a script full of loose functions, than to use an object oriented approach.


Solution:2

I would bite the bullet manually rename each function call for the smaller library (I'm guessing that would be the Forums one). Good luck.


Solution:3

Rename the functions to is_admin_wp() and is_admin_smf(). Then, define your own is_admin() function. This could be just a simple wrapper:

function is_admin() {      // from what function is_admin was called?      list (, $last) = debug_backtrace();      if (strpos($last['file'], 'wordpress') >= 0) {          $fn = 'is_admin_wp';      } else {          $fn = 'is_admin_smf';      }      $args = func_get_args();      return call_user_func_array($fn, $args);  }  


Solution:4

A possibility would be to use PHP 5.3, which brings support for namespaces. I don't know the details of the implementation but it should enable you to wrap the libraries in different namespaces.

Unfortunately 5.3 has still not hit the stable release. If you can't/don't want to use it, the only option I see that doesn't involve renaming would be this: create separate two PHP scripts, start them in different interpreters, and have them communicate somehow (a pipe, socket, tempfile).


Solution:5

Luckly for me this was the comment found in the decleration of is_admin in Simple Machine Forums.

// Grudge chickens out and puts this in for combatibility. This will be ripped out on day one for SMF 1.2 though ;)  

Seems its not needed anyway... A little anoying that I will have to remember to remove this when I upgrade every time though...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »