开发者

Is there a way to avoid the "redeclared function" fatal error while defining functions within functions in PHP?

I've been implementing a certain plugin (dtabs) on my page in Wordpress but after upgrading to the latest version, I found that I now have an error the 2nd time I call the main function called dtab_list_tabs().

The way it works is开发者_运维问答, the plugin gets include_once'd but the main function is called however many times you want to place tabs in your layout. I have 2 such calls to dtab_list_tabs().

Now, the problem is, for whatever reason the developer decided to include another function directly inside dtab_list_tabs() called current_tab(). Because it's declared within a function, apparently PHP tries to redeclare it as soon as you call the parent function the 2nd time, which doesn't make any sense to me.

PHP Fatal error: Cannot redeclare current_tab() (previously declared in .../wp-content/plugins/dtabs/dtabs.php:1638) in .../wp-content/plugins/dtabs/dtabs.php on line 1638

The code for that revision is at http://plugins.svn.wordpress.org/!svn/bc/208481/dtabs/trunk/dtabs.php

What I'm trying to figure out is whether there is a way to tell PHP that yeah... it has an internal function, which is a perfectly valid PHP paradigm as far as I know, so don't redeclare it and fail.

As for the situation at hand, I have removed current_tab() as it doesn't appear to be used.


You can use function_exists() to test if a function with that name has already been defined. If you make the definition conditional ( if(something) { function foo() {...} } ) php will "evaluate" the definition only when the condition is met.

function foo() {
  if ( !function_exists('bar') ) {
    function bar() {
      echo 'bar ';
    }
  }

  bar();
}

foo();
foo();

see also: http://docs.php.net/functions.user-defined

(But I'd try to avoid such things all together)


You can wrap your function declaration in an if statement. Use function_exists() to see if the function has been previously declared or not.

if(!function_exists('current_tab')) {
  function current_tab() {
    myMagicCode();
  }
}


You can try this:

if (!function_exists('my_function')) {
  function my_function() {

  }
}

function_exists() - Return TRUE if the given function has been defined

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜