While there has been talk of read-only variables since at least 2012, with even an RFC proposing it on objects, the support does not exist in the language.
One way to achieve a read-only variable (or a collection of read-only variables, as might be important with certain configuration values) is with a mediating container:
class Readonly {
public function __construct(...$vars) {
$this->vars;
}
public function __set($var, $value) {
if (array_key_exists($var, $this->vars)) {
throw new \LogicException("Variable $var is read-only");
} else {
$this->vars[$var] = $value;
}
}
public function __get($var) {
return array_key_exists($var, $this->vars) ? $this->vars[$var] : null;
}
protected $vars = [];
}
Which allows you to create a container of read-only variables:
$config = new Readonly('apikey');
$config->apikey = 'A01AB020'; // this works, first time set
echo $config->apikey;
$config->apikey = '00000000'; // boom! it's "final"