0

Sorry but I have had this problem for months and I didn't find any answer for it. Here is my code:

<?php 

require_once "B.php";

class A 
{
   private static B $inner = new B(); // Line 7
   
   public static function getInstance() : B 
   {
      return self::$inner;
   }
}

?>

I get a Fatal error:

Constant expression contains invalid operations on line 7

Here are my other classes codes: B.php

<?php 

class B 
{
    public function getInfo() : string 
    {
        return "This is " . self::class . " class";
    }
}

?>

And index.php

<?php

require_once "A.php";


echo A::getInstance()->getInfo() . PHP_EOL; 

?>

Can anyone explain to me why I'm getting this error?
I want to know why PHP does not allow me to declare an object as a private static field.

  • From the docs: "Class member variables are called properties. They may be referred to using other terms such as fields, but for the purposes of this reference properties will be used. They are defined by using one of the keywords public, protected, or private, optionally, as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value." – Dirk J. Faber Sep 05 '21 at 09:22
  • 1
    There was a [discussion about](https://wiki.php.net/rfc/calls_in_constant_expressions_poll#vote) this 18 months ago and the consensus was to not add this. At the bottom of that page is a link to the discussion itself on externals. It is possible that the [forthcoming enums](https://stitcher.io/blog/php-enums) in 8.1 might solve this for you, otherwise you’ll want the factory pattern along with possibly lazy loading. – Chris Haas Sep 05 '21 at 12:59

0 Answers0