在 PHP7.4.3 中,我尝试使用类静态变量来引用不同的类静态成员函数,如下所示:
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
第 10 行和第 12 行,我希望调用 ColorT::yellow()
。
12 号线按预期运行。
但在第 10 行,它打印错误:
PHP Fatal error: Uncaught Error: Function name must be a string
php不支持类静态变量引用类静态成员函数吗?
如果支持,那么如何修复第10行提到的错误?
最佳答案
在第 10 行,ColorT::$color
是“黄色”。因此 ColorT::$color()
将调用 yellow()
,而不是 ColorT::yellow()
。
您可以使用callbable ['ColorT', ColorT::$color]
为此,动态调用 ColorT::yellow()
。
示例:
class ColorT {
static $color = "yellow";
static function yellow() {
echo "yellow"."<br>";
}
static function green() {
echo "green"."<br>";
}
}
$method = ['ColorT', ColorT::$color];
$method();
输出:
yellow<br>
另一种方法是在 ColorT 中创建一个方法:
static public function callFunc()
{
[__class__, self::$color]();
}
并使用
ColorT::callFunc(); // "yellow<br>"
您还可以使用is_callable()
进行检查
关于PHP7-类静态变量不支持变量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65739896/