1

I have two static properties I would like to access outside of a class, the second of which I would like to concatenate with the first.

Ex:

<?php
class Constants {
    public static $varToConcat = "bar";
    public static $concat = "foo " . self::$varToConcat;    // <-- How to concatenate?
}
echo Constants::$concat;
?>

The above gives the error:

PHP Fatal error: Constant expression contains invalid operations in ...../Constants.php on line 4

I've tried:

public static $concat = "foo " . $varToConcat;
public static $concat = "foo " . self::$varToConcat;
public static $concat = "foo " . $this->varToConcat;

How can this be done?

Machavity
  • 30,841
  • 27
  • 92
  • 100
voong
  • 13
  • 3
  • Class variable declarations must be a non-evaluated value. – aynber Feb 26 '20 at 19:31
  • [Just use *actual* constants?](https://3v4l.org/4sG4l) Actually not exactly sure why this doesn't work with static properties' initializers, since it works with constants'. – Jeto Feb 26 '20 at 19:34
  • @Jeto Paradigmatically, you are correct. These values will never change; I will use const. – voong Feb 26 '20 at 23:18

2 Answers2

0

If you want to concatenate outside the class do that:

<?php

class War
{
    public static $foo = 'Hello';
    public static $bar = 'World';
}

echo War::$foo. ' ' . War::$bar;

Output:

Hello World
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

There's no way to do what you're talking about because static cannot be dynamic like that. What you could do is create a static method and get it

<?php
class Constants {
    public static $varToConcat = "bar";
    public static $concat = "foo ";

    public static function getConcat() {
        return self::$concat . self::$varToConcat;
    }
}
echo Constants::getConcat();
Machavity
  • 30,841
  • 27
  • 92
  • 100