简体   繁体   中英

How to override a class constant in PHP?

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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM