0

I'd like to assign the result of a count over a constant to a constant. Here is an example of what I am trying to achieve:

class A
{
    private $a = count('Hello'); # PHP Fatal error:  Constant expression contains invalid operations
}

$a = new A();
echo $a->a;

The working equivalent in C++:

#include <iostream>

class A
{
    public:
    const int a = sizeof("Hello");
};

int main(void)
{
    A a = A();

    std::cout << a.a << std::endl;
    return 0;
}

Is there any way to achieve this in PHP without using a constructor or calling a method from outside the class ?

Ra'Jiska
  • 979
  • 2
  • 11
  • 23
  • Is `count` actually the function you need to use? Assigning that to a class property doesn't make a whole lot of sense to me - at compile-time the value would always be exactly the same, so why not just use the number? – iainn Sep 26 '20 at 14:42
  • @iainn Because I plan to use it to assign the count of another array constant. This would ensure that my member always has the right count when I add or remove items in the array. – Ra'Jiska Sep 26 '20 at 14:44
  • I'd say that was the responsibility of the calling code, then. If what you want is a count of the array constant, you write `count(ClassName::ARRAY_CONST)`, not a different constant. A class isn't responsible for providing its data in every different format, it just needs to provide it. – iainn Sep 26 '20 at 14:55

1 Answers1

0

You can't initialize class attributes with the result of expressions. Just simple assignment.

private $a = 5; //valid

But you can do it in the constructor of the class.

class A
{
    private $a.
    
    public function __construct()
    {
        $this->a = count('Hello');
    }
}