Undefined constant error in php 7.2
In addition, for those who are new to wordpress Plugin development and cant seem to figure out what it means to define "Constant" before its used...
Here is an example of what will throw an error:
add_action('wp_enqueue_scripts', myprefix_load_styles);
Declaring a function directly like that in a hook is one way to generate an error like this. Instead:
add_action('wp_enqueue_scripts', 'myprefix_load_styles');
Note, the function name is now inside the quotes. And that should work, if thats your scenario.
I've just created a PHP job to recursively clean up all files in a PHP project and automatically quote all strings which are undefined constants used inside square brackets for the array syntax.
Observation: this fix only targets array usage like $a[key1] which will be automatically transformed into $a['key1']. The clean up process DOES NOT parse and compute a list of defined constants in your project, in order to white-list them for usage without quotes in all possible contexts.
It's recommended to run it for your project on DEV first, check functionality and then push to LIVE.
QUICK USAGE:
git clone https://github.com/eyroot/lx-utils lx-utils
cd lx-utils && composer install --no-dev
php run/cleanUpSquareBrackets.php /path/you/want/to/clean/up
The complete usage instructions and source code are on the page:
https://github.com/eyroot/lx-utils
This is a common warning that occurs whenever PHP has detected the usage of an undefined constant.
Here is an example of constant being defined in PHP:
define('PI', 3.14);
Below is a list of some cases that might cause the issue:
Forgetting to use a $ symbol at the start of a variable name.
$name = "Aniket"; echo name; // forgot to add $ before name
The above code will throw: Notice: Use of undefined constant name – assumed ‘name’. Because there is no dollar sign in front of the variable “name”, PHP assumes that I was trying to reference a constant variable called “name”.
Forgetting to place quotes around strings.
echo $_POST[email];
In the example above, I failed to place quotes around the
$_POST
variable“email”
. This code will throw: Notice: Use of undefined constant name – assumed ’email’.To fix this, I’d obviously have to do the following:
echo $_POST["email"];
According to Deprecated features in PHP 7.2.x you should not use undefined constants because:
Unquoted strings that are non-existent global constants are taken to be strings of themselves.
This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.
You can prevent this E_WARNING
only if you declare the constant value before using it.
In the above question, MODULE_HEADER_SELECT_TEMPLATE_STATUS
is not defined.