可以确定“可调用”是函数还是类方法?

时间:2019-01-23 10:58:58

标签: php

在PHP中,callable是普通函数或类方法。

我想检查可调用对象是(1)一个简单函数还是(2)一个类方法。如果这是一个类方法,如何找到可调用对象的类名?

// The function:
function callable_type( $var ) {
    if ( ! is_callable( $var ) ) {
        return 'no callable';
    }

    $type_info = ... how to check the exact type?

    return $type_info;
}

// Test:
function fn_a() {}
class Cls {
    function fn_b() {}
    static function fn_c() {}
}

$callable1 = 'fn_a';
$callable2 = array( new Cls, 'fn_b' );
$callable3 = 'Cls::fn_c';

echo callable_type( $callable1 ); // echo 'function'
echo callable_type( $callable2 ); // echo 'method of Cls'
echo callable_type( $callable3 ); // echo 'method of Cls'

这有可能吗?

1 个答案:

答案 0 :(得分:2)

is_callable返回可调用名称作为字符串的第三个参数(它是一个引用),我们可以使用它来解析名称。如果包含::,则为类方法,否则为自由函数:

function callable_type( $var ) {
    if ( ! is_callable( $var, false, $name) ) {
        return 'no callable';
    }

    if($name === "Closure::__invoke")
        return "Closure";

    $name = explode("::", $name);

    if(count($name) === 1)
        return "Free function '" . $name[0] . "'";

    return "Class method '" . $name[1] . "' of class '" . $name[0] . "'";
}

与以下输入一起使用:

function fn_a() {}
class Cls {
    function fn_b() {}
    static function fn_c() {}
}

$callable1 = 'fn_a';
$callable2 = array( new Cls, 'fn_b' );
$callable3 = 'Cls::fn_c';

echo callable_type( $callable1 ) . "\n";
echo callable_type( $callable2 ) . "\n";
echo callable_type( $callable3 ) . "\n";
echo callable_type(function() {}) . "\n";

输出:

Free function 'fn_a'
Class method 'fn_b' of class 'Cls'
Class method 'fn_c' of class 'Cls'
Closure