2

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?

2
  • 1
    Would ColorT::{ColorT::$color}(); help? I'm not sure if your priority is to only use the classname once, or just to be able to call the method dynamically in one line. That should work as far back as PHP 5.4. See 3v4l.org/kbBVq Commented Jan 15, 2021 at 16:53
  • @iainn I just want to call the method dynamically in one line and your solution works! Thanks. Commented Jan 15, 2021 at 18:31

1 Answer 1

3

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()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.