recursion.ninja recursion.ninja - 3 months ago 16
PHP Question

Accessing a static method in a static variable definition

I am trying to access a static class method in the definition of a static class variable. I have tried several attempts, but cannot get the code to compile.

Naive Attempt:



<?php
class TestClass {
private static $VAR = doSomething(array());

private static function doSomething($input) {
return null;
}
}
?>


Error:

dev@box:~/php$ php -l TestClass.php
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in TestClass.php on line 3
Errors parsing TestClass.php





Intuitive Attempt:



<?php
class TestClass {
private static $VAR = self::doSomething(array());

private static function doSomething($input) {
return null;
}
}
?>


Error:

dev@box:~/php$ php -l TestClass.php
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in TestClass.php on line 3
Errors parsing TestClass.php





Logical Attempt:



<?php
class TestClass {
private static $VAR = static::doSomething(array());

private static function doSomething($input) {
return null;
}
}
?>


Error:

dev@box:~/php$ php -l TestClass.php
PHP Fatal error: "static::" is not allowed in compile-time constants in TestClass.php on line 3
Errors parsing TestClass.php





Desperate Attempt:



<?php
class TestClass {
private static $VAR = $this->doSomething(array());

private static function doSomething($input) {
return null;
}
}
?>


Error:

dev@Dev08:~/php$ php -l TestClass.php
PHP Parse error: syntax error, unexpected '$this' (T_VARIABLE) in TestClass.php on line 3
Errors parsing TestClass.php





The task seems so simple, use the static method to define the static variable, but I can't figure out how to correctly access the static method in the context of static variable declaration.

How do you call a static method in a static variable definition in
PHP v5.5.3
?

Answer

Correct attempt:

<?php
class TestClass {
  private static $VAR = null;

  private static function doSomething($input) {
    return null;
  }

  public static function Construct(){
      self::$VAR = self::doSomething(array());
  }
}
TestClass::Construct();
?>

You CAN initialize a static to a scalar and an array. You CAN NOT initialize it with a function call. So you need a public method that can be invoked to initialize statics if you need things to be private.

If they were public, you could have done:

TestClass::$VAR = TestClass::doSomething(array());

right after the class declaration or when you want to instantiate it.

PROOF

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. from PHP.net/Static