0

The example below has a syntax error because of the following code:

"another_key" => [ 2 => self::$someStr ] 

Using something such as:

"another_key" => [ 2 => "bar" ] 

Is correct syntax. Is there any way to access $someStr instead of hard coding the string?

<?php class Foo { protected static $someStr = 'bar'; private static $arr = [ "some_key" => [ 1 ], "another_key" => [ 2 => self::$someStr ] ]; } 
1
  • 1
    As per the PHP Docs: [Property] declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated. Using self::$someStr requires run-time evaluation Commented Oct 5, 2017 at 16:34

2 Answers 2

2

You cannot access static variables inside of the declaration of other static variables. You can either declare a class constant or initialize it by accessing via a function. A class constant would look like this:

class Foo { const someStr = 'bar'; private static $arr = [ "some_key" => [ 1 ], "another_key" => [ 2 => self::someStr ] ]; } 

Or using a function:

class Foo { private static $someStr = 'bar'; private static $arr = [ "some_key" => [ 1 ], "another_key" => [ 2 => null ] ]; private static function setKey(){ self::$arr['another_key'] = [2 => self::$somStr]; } } 

You'd then have to call Foo::setKey() at some point before accessing the variable.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to access a property to set the value of another property you should be doing it in the class' constructor. Something like this:

class Foo { protected static $someStr = 'bar'; private static $arr = [ 'some_key' => [1] ]; public function __constructor() { self::arr['another_key'] = [2 => self::$somStr]; } } 

For this to work you will need to instantiate your class.

You can view some examples on property declarations in the PHP documentation.

1 Comment

This solution assumes that the class has been instantiated at some point in the stack, since variables are static that isn't necessarily true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.