Are constants as evil as global variables and solitary?

I have heard many times in this forum that using a global variable is a dead sin, and implementing a singleton is a crime.

It seemed to me that the good old constants carry all the features of these dishonest practices: they are available all over the world and, without a doubt, they are introducing a global state.

So the question is, should we also declare jihad to constants and use all modern things like DI, IoC or other stylish words, instead?

+4
source share
3 answers

, , , , .

, , , ( ) , , , . , , , , .

, ... , . , , , , , , , .

.

, PHP-, define , - . : ; - . -, , . , , .

, PHP; , , .

+7

, , . . - . , ,

class Foo
{
    public function doSomething()
    {
        if (ENV === ENV_DEV) {
            // do something this way
        } else {
            // do something that way
        }
    }
}

doSomething, , . , , , .

, ,

public function log($message)
{
    fwrite(LOGFILE, $message);
}

, - ,

define('LOGFILE', fopen('/path/to/logfile'));

, ENV. , , - . , . , , , -, , , , . , LOGFILE . .

, . , , , , , , .

, . , . , .

, - , . , , , . API.

Value, :

class Environment
{
    private $value;

    public function __construct($value)
    {
        $this->assertValueIsAllowedValue($value);
        $this->value = $value;
    }

    public function getValue() {
// …

, , , , , . , YMMV. . , , , .

:

+6

.

, , , . / , , , , . , , concurrency parallelism.

( ) . , , . , . , , , . ( !)

- . , - . (, ++) , . , ( ).

EDIT. To stop briefly, you mentioned in your question that global constants introduce "global state ever." This is not very accurate, because the global constant (or should be) is fixed just like the source code is fixed. It determines the static nature of the program, while “state” is usually understood as a dynamic concept of runtime (i.e., material that can change).

+4
source

All Articles