Freemius / freemius-php-sdk

https://freemius.com
22 stars 13 forks source link

Fatal error - Cannot declare class Freemius_Api_Base, because the name is already in use #17

Closed daigo75 closed 2 years ago

daigo75 commented 2 years ago

🐞 bug report

Behavior: I tried some scheduled tasks via wp-cli, and the following notice appeared An error of type E_ERROR was caused in line 50 of the file /path-to/src/vendor/freemius/php-sdk/freemius/FreemiusBase.php](http://example.org/path-to/src/vendor/freemius/php-sdk/freemius/FreemiusBase.php). Error message: Cannot declare class Freemius_Api_Base, because the name is already in use.

Affected line https://github.com/Freemius/freemius-php-sdk/blob/master/freemius/FreemiusBase.php#L46 to https://github.com/Freemius/freemius-php-sdk/blob/master/freemius/FreemiusBase.php#L50

Cause The affected lines contain the following code:

if ( class_exists( 'Freemius_Api_Base' ) ) {
  return;
}   

abstract class Freemius_Api_Base {
  // Class details
}

Although there is a class_exists() check before the declaration of the class, this doesn't always seem to cause the return line to actually stop the execution and prevent the class from being declared. This is something I noticed in the past with other classes, unrelated to Freemius. The if class exists -> return logic doesn't always seem to work.

Solution The solution I applied was to replace the if class exists -> return with a condition that declares the class only when it doesn't exist. That is:

if ( !class_exists( 'Freemius_Api_Base' ) ) {
  abstract class Freemius_Api_Base {
    // Class details
  }
}   

This produces more consistent results, and prevents fatal errors.

Versions: (*)

vovafeldman commented 2 years ago

Thanks, @daigo75 👍