I am trying to initialize some values inside a class and save them in constant and access them outside, in different part of my code.
<?php
class Config {
public static function initialize() {
define('TEST',"This is a Constant");
}
}
$config = Config::initialize();
// do something with the constants
Can I access it outside?
A Class constant uses the
const
keyword. You don't define them using the define function. Just like this:In PHP, you cannot dynamically set the value of a constant, but you can get a similar behaviour with a public static variable. ie.
The downside is, there is nothing stopping other code from setting the value from outside the class. If you need protection against this, you should use a getter function approach. eg.