0

As I know we can't redefine a constant in PHP. So if I do:

define("DEVELOPMENT", true);

theoretical I can not redefine it using:

define("DEVELOPMENT", false); (or) const DEVELOPMENT = false;

The problem is PHP let me do that. It lets me redefining a constant without throwing any error. Display error is on (I got any other error):

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);

What to do so constants can't be redefined and to get error if I try?

My PHP version is 7.2.17

2 Answers2

0

To report all php error

error_reporting(E_ALL);

To report all php errors except notices

error_reporting(E_ALL & ~E_NOTICE);

And in your case, you are redefining a constant that has been already defined show PHP throws a notice. By using

error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);

You are telling PHP not to report any kind of notices or warnings. You should remove them.
To get all warning and notices use

error_reporting(E_ALL);

Fore more information refer to the official doc, and have a look on examples.

sujeet
  • 3,480
  • 3
  • 28
  • 60
0

There is no error, but there is a notice.

Notice: Constant DEVELOPMENT already defined

This is why it is important to never switch notice off.

error_reporting(E_ALL); // E_ALL reports all problems including notices, warnings and deprecations

Of course, because it is a constant the second define becomes non-executable piece of code, because you can't redefine the constant, the value remains as it was originally defined.

define("DEVELOPMENT", true);
define("DEVELOPMENT", false);

var_dump(DEVELOPMENT); // prints out bool(true)

Try it online: https://3v4l.org/7i8XL

This might not be a huge issue if you have small personal project, but because constants are always in global namespace, in a large project with loads of external dependencies some constants might clash with each other. If you have PHP notices enabled you might be able to see this problem quicker. Another option is to always create properly named constants, with names unlikely to clash with other constants.

define("MY_COOL_LIBRARY_DEVELOPMENT", false);
Dharman
  • 30,962
  • 25
  • 85
  • 135