I have a class with the following schema
class MyClass
{
const x = 'abc';
const y = '123';
function _contruct() {}
}
Is there any way for me to have the constants remain unset in the class body, and be set dynamically after the constructor has been called? E.g something like this:
class MyClass
{
const x;
const y;
function _contruct()
{
$this->setStuff();
}
function setStuff()
{
$this->x = Config::getX();
$this->y = Config::getY();
}
}
No. Class constants (and global or namespace constants defined with the const
keyword) have to be literal values and must be set prior to runtime. That's where they differ from the old-school define()
constants that are set at runtime. It's not possible to change or set a const
constant during the execution of a script.
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
from PHP manual: Class Constants
So that's possible:
define('MY_CONST', someFunctionThatReturnsAValue());
But that's not:
const MY_CONST = someFunctionThatReturnsAValue();
// or
class MyClass {
const MY_CONST = = someFunctionThatReturnsAValue();
}
// or
namespace MyNamespace;
const MY_CONST = someFunctionThatReturnsAValue();
And by using $this
in your example one might assume that you try to set the constants on the instance level but class constants are always statically defined on the class level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With