75

What is the best way to define constants that may be used by a number of classes within a namespace? I'm trying to avoid too much inheritance, so extending base classes is not an ideal solution, and I'm struggling to find a good solution using traits. Is this in any way possible in PHP 5.4 or should a different approach be taken?

I have the following situation:

trait Base
{
    // Generic functions
}

class A 
{
    use Base;
}

class B 
{
    use Base;
}

The problem is that it is not possible to define constants in PHP traits. Ideally, I would want something like the following:

trait Base
{
    const SOME_CONST = 'someconst';
    const SOME_OTHER_CONST = 'someotherconst';

    // Generic functions
}

Then these could be accessed though the class that applies the trait:

echo A::SOME_CONST;
echo B::SOME_OTHER_CONST;

But due to the limitations of traits this isn't possible. Any ideas?

6

7 Answers 7

109

I ended up using user sectus's suggestion of interfaces as it feels like the least-problematic way of handling this. Using an interface to store constants rather than API contracts has a bad smell about it though so maybe this issue is more about OO design than trait implementation.

interface Definition
{
    const SOME_CONST = 'someconst';
    const SOME_OTHER_CONST = 'someotherconst';
}

trait Base
{
    // Generic functions
}

class A implements Definition
{
    use Base;
}

class B implements Definition
{
    use Base;
}

Which allows for:

A::SOME_CONST;
B::SOME_CONST;
12
  • 109
    So interfaces can have constants...but traits can't? PHP gets weirder and weirder. Jun 10, 2015 at 19:17
  • 8
    @Adambean overriding a constant defeats the purpose of the constant, it isn't meant to change.
    – aknosis
    Feb 8, 2018 at 18:55
  • 1
    Yet if I want to use a value within the trait's code implementation, it's not possible.
    – SOFe
    May 4, 2018 at 15:28
  • 11
    @Aknosis I personally see it more than a constant doesn't change value during its lifecycle. That doesn't mean it cannot be redefined with another value, when extending a class (and use [e.g.] static::VALIDATION_REGEX to get the late-static-bound value) Aug 29, 2018 at 15:06
  • 2
    PHP 'bug' #75060
    – Jake
    Jun 21, 2020 at 1:13
50

You could also use static variables. They can be used in the class or the trait itself. - Works fine for me as a replacement for const.

trait myTrait {
    static $someVarA = "my specific content";
    static $someVarB = "my second specific content";
}

class myCustomClass {
    use myTrait;

    public function hello()
    {
        return self::$someVarA;
    }
}
3
  • 17
    I know this is old, but dont you want to use const to not be able to change the value?
    – visualex
    Aug 2, 2016 at 14:30
  • 5
    You can't use constants in a Trait.
    – cawhite78
    May 9, 2017 at 16:47
  • You can't at present, PHP 8.2, but hopefully the PHP community sees such feedback as this is quite irritating. They've made a whole other can of worms with readonly and are still left with this being a problem Dec 4, 2022 at 10:59
14

PHP 8.2 (Dec 2022) has Constants in Traits1. To quote from the PHP Manual:

Traits can, as of PHP 8.2.0, also define constants.

Compare with Example #14 Defining Constants and see the example:

trait Foo {
    public const FLAG_1 = 1;
    protected const FLAG_2 = 2;
    private const FLAG_3 = 2;
 
    public function doFoo(int $flags): void {
        if ($flags & self::FLAG_1) {
            echo 'Got flag 1';
        }
        if ($flags & self::FLAG_2) {
            echo 'Got flag 2';
        }
        if ($flags & self::FLAG_3) {
            echo 'Got flag 3';
        }
    }
}

  1. PHP 8.2 New Features: Constants in Traits (RFC, CHANGE)
12

To limit the scope of your constants, you can define them inside a namespace:

namespace Test;

const Foo = 123;

// generic functions or classes

echo Foo;
echo namespace\Foo;

A downside of this approach is that autoloading won't work for constants, at least not for 5.4; the typical way around this is to wrap those constants in a static class, i.e.:

namespace Test;

class Bar
{
    const Foo = 123;
}
2
  • Interesting idea. I didn't realise you could access namespaced constants directly. The problem is this library is PSR-0 autoloaded so I'm afraid this approach wouldn't work. Thanks for the answer though.
    – t j
    Jun 24, 2014 at 3:03
  • 1
    @orciny Well, autoloading would work if you wrap those constants inside a static class; not the shiniest example of beautiful code, but it would work :)
    – Ja͢ck
    Jun 24, 2014 at 3:06
9

Not a good one, but maybe...

trait Base
{
    public static function SOME_CONST()
    {
        return 'value1';
    }

    public static function SOME_OTHER_CONST()
    {
        return 'value2';
    }

    // generic functions
}

class A
{
    use Base;
}

class B
{
    use Base;
}

echo A::SOME_CONST();
echo B::SOME_OTHER_CONST();
2
  • Note to those that didn't follow, these are static methods, not constants.. they look a bit like constants when used though. If you were to do this and you wanted these methods to behave more like constants, you would want to prefix the methods with the keyword final to ensure they couldn't be overriden (same behaviour as constants).
    – John Hunt
    Mar 5, 2020 at 14:50
  • 2
    @John Hunt, final doesn't work for traits, see stackoverflow.com/a/33481511/251735
    – Jekis
    Mar 9, 2020 at 5:43
4

Starting from PHP 8.1, it is possible to use readonly properties in traits.

<?php
trait A
{
    public readonly int $variable;
    
    protected function initA(int $newValue){
        $this->variable = $newValue;
    }

    public function changeVariable(int $newValue){
        $this->variable = $newValue;
    }
}

class B {
    use A;

    public function __construct() {
        $this->initA(1);
    }
}

$b = new B();
$b->changeVariable(5); // should faild: Fatal error: Uncaught Error: Cannot modify readonly property B::$variable
-4

Something else to consider is whether or not you can use an abstract class instead, and then inherit.

abstract class Base
{
    const A = 1;
    const B = 2;
}

class Class1 extends Base {}
class Class2 extends Base {}

echo Class1::A;
echo Class2::B;

Of course, part of the reason for traits is replace complex inheritance trees with composition. Depends on the situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.