Is it possible to redefine PHP constants?

2019-04-19 22:23发布

问题:

Is it possible to redefine class constants (in PHP)?

e.g.

class B {
const C_ThisIsAConstant = 1;
}

class A extends B {
 self::C_ThisIsAConstant = 2;
}

回答1:

No, of course not. Then they wouldn't be "constants."



回答2:

You can't redefine "constants" because they are contant.

If you're trying to change a constant defined in an included file, then you can defining the constant before the include:

define ("PROCESS_NAME", "MIKE");
/* ... code ... */
include ("/path/to/included_file.php"); // also defines "PROCESS_NAME"
/* ... code ... */

PROCESS_NAME will be "MIKE".



回答3:

First: No, it is not possible to redefine class constants. Its impossible in every language, because otherwise a constant wouldnt be constant.

But what you are doing is possible, because you dont redefine a class constant, instead you define a one unique constant for every class.



回答4:

<?php

class B {
    const C_ThisIsAConstant = 1;
}

class A extends B {
    const C_ThisIsAConstant = 2;
}

var_dump(A::C_ThisIsAConstant);

It outputs int(2).

http://codepad.org/GQR9HI5M



回答5:

I have published my framework YAPAF on github.com. Let's call it alpha-state. Anyhow, YAPAF is able to change the value of a class constant (see https://github.com/SchulteMarkus/YAPAF/blob/master/tests/ManipulateConstantTest.php).