How to define constant in class constructor?

2019-04-25 06:57发布

问题:

Can I define a class constant inside the class constructor function ?

(based on certain conditions)

回答1:

That goes against the idea of class constants - they should not be dependent on a specific instance. You should use a variable instead.

However, if you insist on doing this, are very adventurous and can install PHP extensions, you can have a look at the runkit extension that allows to modify classes and their constants at runtime. See this doc: http://www.php.net/manual/en/function.runkit-constant-add.php



回答2:

I don't think you can.

It wouldn't make sense, either - a class constant can be used in a static context, where there is no constructor in the first place.

You'll have to use a variable instead - that's what they're there for.



回答3:

Try look here:

http://php.net/manual/en/language.oop5.constants.php

http://php.net/manual/en/language.oop5.static.php

Hope this helps.