vbnet3d
vbnet3d

Reputation: 1151

PHP Cannot redeclare function/Call to undefined function

I am using WooCommerce on Wordpress 4.7.1. Previously, I was running 4.7.0. When Wordpress automatically upgraded to 4.7.1, I suddenly began seeing checkouts fail to redirect to the "Thank you" page, and the UI showed that a fatal error had occurred.

Turning on debugging revealed the following error:

PHP Fatal error: Cannot redeclare get_cc() (previously declared in .../templates/emails/email-addresses.php:36) in .../templates/emails/email-addresses.php on line 36

I also confirmed that this file is never directly called with require, require_once, include, or include_once. It is, however, called with wc_get_template().

A quick search brought me to this similar question. So I added the following to email-addresses.php:

if (!function_exists('get_cc')) {
    function get_cc( $code ) {
        ... function body
    }
}

After making this change, I now receive the following error in the debug log:

PHP Fatal error: Call to undefined function get_cc() in .../templates/emails/email-addresses.php on line 32

This means that, for whatever reason, PHP believes that the function get_cc already exists, but at the same time it is undefined.

I was not the original developer. I took over the project from a contractor who is not available. It does seem clear that this file is heavily modified from the original. I am certain that the value returned by the function must be kept, so I cannot just comment out the call.

Given the information above, what options do I have to either workaround or fix this issue?

Upvotes: 1

Views: 1770

Answers (1)

vbnet3d
vbnet3d

Reputation: 1151

It turns out that, unlike a standard function definition in PHP, function definitions wrapped in if (!function_exists('function_name')) { ... } block must precede any call to that function.

In this case, the function definition (line 36) followed the call (line 32). This caused the function to appear to PHP as undefined:

// Not working!
$value = get_cc($code);

if (!function_exists('get_cc')) {
    function get_cc( $code ) {
        ... 
    }
}

Switching the order so that the function definition came first fixed the issue:

// Working!
if (!function_exists('get_cc')) {
    function get_cc( $code ) {
        ... 
    }
}

$value = get_cc($code);

As of right now, PHP's documentation does not mention this issue.

Upvotes: 2

Related Questions