Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 533
Artem Russakovskii Avatar asked Dec 01 '25 01:12

Artem Russakovskii


1 Answers

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)

like image 164
VolkerK Avatar answered Dec 03 '25 13:12

VolkerK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!