我们可以使用数组来存储PHP5中的静态方法,比如C++11吗?

我们可以使用数组来存储PHP5中的静态方法,比如C++11吗?,php,Php,我试图将一些静态方法放入PHP5中的数组中。我写了以下代码: <?php class A{ public static func(){ echo "A::func"; } } $list_of_methods = array( A::func ); 在C++11中,我们可以将静态方法放在如下向量中: #include<iostream> #include<vector> using namespace std; class

我试图将一些静态方法放入PHP5中的数组中。我写了以下代码:

<?php
class A{
    public static func(){
        echo "A::func";
    }
}

$list_of_methods = array(
    A::func
);
在C++11中,我们可以将静态方法放在如下向量中:

#include<iostream>
#include<vector>
using namespace std;
class Test{
public:
        static void func(){
                cout<<"Test::func()"<<endl;
        }
};

int main(){
        vector<void(*)()>list_of_methods;
        list_of_methods.push_back(Test::func);
        list_of_methods[0]();
        return 0;
}
我想知道PHP5中是否有类似C++11的实现


也可以使用PHP7。

PHP中的可调用项可以是静态方法。它基本上只是一个字符串数组:

Test::func();

// can also be written as:
call_user_func(array('Test', 'func'));
因此,在您的情况下,您必须:

$list_of_methods = array(
    array('A' ,'func')
);

call_user_func($list_of_methods[0]);
对于非静态方法,第一项不应是类名的字符串,而应是对象本身:

$test = new Test();
$test->func();

// can also be written as:
$test = new Test();
call_user_func(array($test, 'func'));

查看有关PHP中可调用项的更多信息。

您想这样做有什么特别的原因吗,因为我感觉您正在尝试破解另一个问题。类似于@tereško的东西我想要的是使用数组来存储不同类的getInstance。这样我就可以写汽车了;车辆['Bus']获取汽车和公共汽车实例。我想把这个机制用于其他操作,这是一个糟糕的方法。相反,您应该使用依赖注入;新的$class_name,定义一类车辆并将其扩展到汽车和公共汽车?您甚至可以声明接口和特性。您正在尝试打破OOP风格。@Quasimodo's如果没有适当的上下文,您告诉他做的事情也不会好多少。static函数可以直接调用$list_of_方法[0];
$test = new Test();
$test->func();

// can also be written as:
$test = new Test();
call_user_func(array($test, 'func'));