作为函数调用的 PHP 类

标签 php class function

有没有办法编写一个可以像函数一样调用的类?我的意思是这样的:

class test{}
$test = new test;
$test();

我尝试使用 __call 魔术方法,但它只能在访问其上不存在的方法时使用。也许可以使用 SPL 类或接口(interface)来完成?

最佳答案

使用__invoke magic method :

class test{
    public function __invoke()
    {
        return 'fooo';
    }
}

$test = new test;
print $test();

但是您需要 PHP 5.3。

根据您想要执行的操作,另一种选择可能是使用 closure .

关于作为函数调用的 PHP 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330392/

相关文章:

python - 无法使用基类创建其子类的实例

python - 我可以将函数设置为默认参数吗?

php - 不是测试的代码接收公共(public)方法

php - date_default_timezone_set 不起作用,为什么?

c++ - 拥有 "Dynamic" vector 类

javascript - 类没有定义onClick事件

c - C 中 const 限定函数的行为

void 类型参数的 C++ 错误

php - PSR 标准中哪里规定类型声明后不能有变量名?

php - MYSQL LEFT JOIN 未返回 id