Is it possible to redefine PHP constants?

2019-04-19 22:34发布

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;
}

5条回答
We Are One
2楼-- · 2019-04-19 23:05

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

查看更多
仙女界的扛把子
3楼-- · 2019-04-19 23:08

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-04-19 23:11

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).

查看更多
霸刀☆藐视天下
5楼-- · 2019-04-19 23:15

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".

查看更多
手持菜刀,她持情操
6楼-- · 2019-04-19 23:19
<?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

查看更多
登录 后发表回答