How to define a constant in a class constructor?

Is it possible to define a class constant inside a class constructor function?

(based on certain conditions)

+6
source share
3 answers

This contradicts the idea of ​​class constants - they should not depend on a specific instance. Instead, you should use a variable.

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

+8
source

I do not think you can.

This also makes no sense - the class constant can be used in a static context, where there is no constructor in the first place.

Instead, you have to use a variable - what they are for.

+3
source

Source: https://habr.com/ru/post/895570/


All Articles