How to override a class constant in PHP?
constants, oop, php
Solution
If your users are extending your class, they can redefine the constant just fine:
class Foo extends Bar {
const BAZ = 42;
}
It doesn't matter whether `Bar` already defines a `BAZ` constant or not. All you have to do in your code is make sure you're referring to the "current classes" constant using late static binding:
public function useConst() {
echo static::BAZ;
}
Otherwise, you have the option of doing this:
if (!defined('BAZ')) {
define('BAZ', 42);
}
class Bar {
const BAZ = BAZ;
}
That's not really very elegant though. You should rather be using getters and setters on your class to allow configuration, rather than using constants for this purpose:
Bar::setBaz(42);
Problem
When working with constants, I've always tried to define constants like the following which allows end-users to override their values. ``` if ( ! defined( 'MY_CONST' ) ) define ( 'MY_CONST', 10 ); ``` I've now started to work with classes (OOP) and would like to know if there's a way to define a class constant that will allow the value to be overridden by end-users? Refs: - http://php.net/manual/en/function.define.php - http://php.net/manual/en/language.oop5.constants.php