Search code examples
phpstatic-methodsstatic-membersstatic-variables

PHP7 - class static variable doesn't support variable function


In PHP7.4.3, I'm trying to use class static variable to refer to different class static member functions as below:

1  class ColorT {
2    static $color = "yellow";
3    static function yellow() {
4        echo "yellow"."<br>";
5    }
6    static function green() {
7        echo "green"."<br>";
8    }
9  }

10 ColorT::$color();  //ColorT::yellow() function is expected to be called

11 $global_color = "yellow";
12 ColorT::$global_color();  //ColorT::yellow() function is expected to be called

Both line 10 and line 12, I expect ColorT::yellow() to be invoked.
Line 12 works as expected.
But in line 10, it print error :

PHP Fatal error: Uncaught Error: Function name must be a string

Doesn't php support class static variable referring to class static member functions?
If it's supported, then how to fix the error mentioned in line 10?


Solution

  • In line 10, ColorT::$color is "yellow". So ColorT::$color() would call yellow(), not ColorT::yellow().

    You could use the callbable ['ColorT', ColorT::$color] for this, to call ColorT::yellow(), dynamically.

    Example :

    class ColorT {
      static $color = "yellow";
      static function yellow() {
          echo "yellow"."<br>";
      }
      static function green() {
          echo "green"."<br>";
      }
    }
    
    $method = ['ColorT', ColorT::$color];
    $method();
    

    Output :

    yellow<br>
    

    Another way is to create a method in ColorT :

    static public function callFunc() 
    {
        [__class__, self::$color]();
    }
    

    and use

    ColorT::callFunc(); // "yellow<br>"
    

    You can also check using is_callable()