Hi @vita1234
The error you’re encountering is due to PHP’s restriction against redeclaring functions with the same name. When both SnippetA and SnippetB define snipA(), activating both leads to a fatal error.
- Function Existence Check: Use
if (!function_exists('function_name')) to ensure a function is defined only once.
- Function Calls: Before calling a function from another snippet, verify its existence with
function_exists('function_name') to avoid errors if the defining snippet is inactive.
SnippetA:
error_log("snip AAA");
if (!function_exists('snipA')) {
function snipA() {
error_log("snipA()");
}
}
snipA();
SnippetB:
error_log("snip BBB");
if (!function_exists('snipB')) {
function snipB() {
error_log("snipB()");
}
}
snipB();
if (function_exists('snipA')) {
snipA();
}
Best regards,
Pau.
Well thank you it actually works 😊🙏
But your explanation doesn’t make sense to me.
You explained that “[it] is due to PHP’s restriction against redeclaring functions with the same name”
But I didn’t redeclare snipA(). So do you know what may be actual explanation?
(I mean I’m very happy that it just works like this. But I’m still curios about reason…)
I’m guessing maybe Code Snippet tries to provide it’s own function snipA() and thus break it by redeclaring?
Plugin Author
Imants
(@0aksmith)
Hi @vita1234 !!
Dear apologies for letting you wait on this explanation.
The issue occurs because the Code Snippets plugin executes each snippet in isolation but still within the same PHP runtime environment. When SnippetB calls snipA(), it requires snipA() to be defined, which means SnippetA must have been executed beforehand.
However, the problem arises when you later try to save SnippetA. Since SnippetB already executed snipA() in the same environment, trying to save (and potentially re-run) SnippetA causes a function redeclaration error, which is a fatal error in PHP. This results in the 500 error when saving.
Even though calling snipA() from SnippetB works because the function is already defined, the issue surfaces when reloading or modifying the snippet that originally defined it.
The solution is to use if (!function_exists('snipA')) before defining the function in both snippets, preventing PHP from attempting to redeclare it. This ensures that no matter which snippet runs first, it won’t cause conflicts.
Please note, that this is a side effect of how PHP handles function definitions across multiple executed snippets.