1

Please help me to understand this:


1 <?php
2 class test{
3   private $a = "a";
4   private $b = $a."b";
5   
6   function __construct(){
7     echo $this->b;
8   }
9 }

I get Constant expression contains invalid operations on line 4

Why? I tried also with $this->a but it also do not work.

Please explain it to me.

Update

For some strange reason this works


class test{
  private const a = "a";
  private $b = self::a."b";
    
  function __construct(){
    echo $this->b;
  }
}

I can remember now that it does not work. But can someone please explain it to me.

Anylyn Hax
  • 301
  • 2
  • 10
  • 2
    You can't perform operations in class property declaration. If you want to change the value of `b` to be `a` plus something, do it in the constructor. – El_Vanja Mar 29 '21 at 15:58
  • @El_Vanja thank you. That's really bad news. – Anylyn Hax Mar 29 '21 at 16:05
  • Honestly, it seems like you shouldn't even have the `b` property, only a getter that takes `a` and appends whatever you need. Because if you change `a`, then you also need to change `b` if it's a property. – El_Vanja Mar 29 '21 at 16:06
  • After the edit, you concatenate two *constant* expressions. In the first one, you used a variable. – El_Vanja Mar 29 '21 at 16:16
  • @El_Vanja so operations with constants are permitted but operations with variables not? – Anylyn Hax Mar 29 '21 at 16:18
  • 1
    Exactly, because it seems variable values aren't resolved yet at that point during compilation. See [this question](https://stackoverflow.com/questions/40171546/php-error-fatal-error-constant-expression-contains-invalid-operations). – El_Vanja Mar 29 '21 at 16:23

1 Answers1

0

The property declaration may include an initialization, but this initialization must be a constant value (->PHP-manual). This

private $b = $this->a."b";

throw a 'Fatal error: Constant expression contains invalid operations..' because $this->a is not a constant. The PHP parser cannot check whether $this->a always remains constant. For PHP, $this->a is generally a variable.

That, however, works flawlessly.

class test
{
  private const a = "a";
  private $b = self::a."b";
}

self::a and "b" are constants.

jspit
  • 7,276
  • 1
  • 9
  • 17