略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Callback / Callable 类型

2024-11-14

Callback / Callable 类型

回调可以通过 callable 类型声明来表示。

一些函数如 call_user_func()usort() 可以接受用户自定义的回调函数作为参数。回调函数不止可以是简单函数,还可以是对象的方法,包括静态类方法。

传递

PHP是将函数以string形式传递的。 可以使用任何内置或用户自定义函数,但除了语言结构例如:array()echoempty()eval()exit()isset()list()printunset()

一个已实例化的 object 的方法被作为 array 传递,下标 0 包含该 object,下标 1 包含方法名。 在同一个类里可以访问 protected 和 private 方法。

静态类方法可以不实例化 object 传递,只需要在下标为 0 的位置传递类名而不是 object ,或者传递 'ClassName::methodName'

回调参数不仅可以使用普通的用户自定义函数,也接受 匿名函数箭头函数

注意:

从 PHP 8.1.0 开始,还可以使用 First-class 可调用语法 创建匿名函数。

通常情况下,任何实现了 __invoke() 的对象都可以传入回调参数。

示例 #1 回调函数示例

<?php 

// 回调函数示范
function my_callback_function() {
    echo 
'hello world!';
}

// 回调方法示范
class MyClass {
    static function 
myCallbackMethod() {
        echo 
'Hello World!';
    }
}

// 类型 1:简单的回调
call_user_func('my_callback_function'); 

// 类型 2:静态类方法回调
call_user_func(array('MyClass''myCallbackMethod')); 

// 类型 3:对象方法回调
$obj = new MyClass();
call_user_func(array($obj'myCallbackMethod'));

// 类型 4:静态类方法回调
call_user_func('MyClass::myCallbackMethod');

// 类型 5:父级静态类回调
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A

// 类型 6:实现 __invoke 的对象用于回调
class {
    public function 
__invoke($name) {
        echo 
'Hello '$name"\n";
    }
}

$c = new C();
call_user_func($c'PHP!');
?>

示例 #2 使用 Closure 的示例

<?php
// 闭包
$double = function($a) {
    return 
$a 2;
};

// 这是数字范围
$numbers range(15);

// 这里使用闭包作为回调,
// 将范围内的每个元素数值翻倍
$new_numbers array_map($double$numbers);

print 
implode(' '$new_numbers);
?>

以上例程会输出:

2 4 6 8 10

注意:

在函数中注册有多个回调内容时(如使用 call_user_func()call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。

add a noteadd a note

User Contributed Notes 18 notes

up
268
andrewbessa at gmail dot com
10 years ago
You can also use the $this variable to specify a callback:

<?php
class MyClass {

    public
$property = 'Hello World!';

    public function
MyMethod()
    {
       
call_user_func(array($this, 'myCallbackMethod'));
    }

    public function
MyCallbackMethod()
    {
        echo
$this->property;
    }

}
?>
up
209
steve at mrclay dot org
9 years ago
Performance note: The callable type hint, like is_callable(), will trigger an autoload of the class if the value looks like a static method callback.
up
186
computrius at gmail dot com
8 years ago
When specifying a call back in array notation (ie. array($this, "myfunc") ) the method can be private if called from inside the class, but if you call it from outside you'll get a warning:

<?php

class mc {
   public function
go(array $arr) {
      
array_walk($arr, array($this, "walkIt"));
   }

   private function
walkIt($val) {
       echo
$val . "<br />";
   }

    public function
export() {
        return array(
$this, 'walkIt');
    }
}

$data = array(1,2,3,4);

$m = new mc;
$m->go($data); // valid

array_walk($data, $m->export()); // will generate warning

?>

Output:
1<br />2<br />3<br />4<br />
Warning: array_walk() expects parameter 2 to be a valid callback, cannot access private method mc::walkIt() in /in/tfh7f on line 22
up
181
Riikka K
7 years ago
A note on differences when calling callbacks as "variable functions" without the use of call_user_func() (e.g. "<?php $callback = 'printf'; $callback('Hello World!') ?>"):

- Using the name of a function as string has worked since at least 4.3.0
- Calling anonymous functions and invokable objects has worked since 5.3.0
- Using the array structure [$object, 'method'] has worked since 5.4.0

Note, however, that the following are not supported when calling callbacks as variable functions, even though they are supported by call_user_func():

- Calling static class methods via strings such as 'foo::doStuff'
- Calling parent method using the [$object, 'parent::method'] array structure

All of these cases are correctly recognized as callbacks by the 'callable' type hint, however. Thus, the following code will produce an error "Fatal error: Call to undefined function foo::doStuff() in /tmp/code.php on line 4":

<?php
class foo {
    static function
callIt(callable $callback) {
       
$callback();
    }
   
    static function
doStuff() {
        echo
"Hello World!";
    }
}

foo::callIt('foo::doStuff');
?>

The code would work fine, if we replaced the '$callback()' with 'call_user_func($callback)' or if we used the array ['foo', 'doStuff'] as the callback instead.
up
188
edanschwartz at gmail dot com
7 years ago
You can use 'self::methodName' as a callable, but this is dangerous. Consider this example:

<?php
class Foo {
    public static function
doAwesomeThings() {
       
FunctionCaller::callIt('self::someAwesomeMethod');
    }

    public static function
someAwesomeMethod() {
       
// fantastic code goes here.
   
}
}

class
FunctionCaller {
    public static function
callIt(callable $func) {
       
call_user_func($func);
    }
}

Foo::doAwesomeThings();
?>

This results in an error:
Warning: class 'FunctionCaller' does not have a method 'someAwesomeMethod'.

For this reason you should always use the full class name:
<?php
FunctionCaller
::callIt('Foo::someAwesomeMethod');
?>

I believe this is because there is no way for FunctionCaller to know that the string 'self' at one point referred to to `Foo`.
up
174
metamarkers at gmail dot com
9 years ago
you can pass an object as a callable if its class defines the __invoke() magic method..
up
151
Yzmir Ramirez
8 years ago
> As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'

You can also use 'self::methodName'.  This works in PHP 5.2.12 for me.
up
8
InvisibleSmiley
1 year ago
If you pass a callable method to a function with a callable type declaration, the error message is misleading:

<?php
class X {
    protected function
foo(): void {}
}

function
bar(callable $c) {}

$x = new X;
$c = [$x, 'foo'];
bar($c);
?>

Error message will be something like "Argument #1 ($c) must be of type callable, array given" while the actual problem here is only the visibility of method "foo". All you need to do is changing it to public (or use a different approach, e.g. with a Closure).
up
100
mariano dot REMOVE dot perez dot rodriguez at gmail dot com
6 years ago
I needed a function that would determine the type of callable being passed, and, eventually,
normalized it to some extent. Here's what I came up with:

<?php

/**
* The callable types and normalizations are given in the table below:
*
*  Callable                        | Normalization                   | Type
* ---------------------------------+---------------------------------+--------------
*  function (...) use (...) {...}  | function (...) use (...) {...}  | 'closure'
*  $object                         | $object                         | 'invocable'
*  "function"                      | "function"                      | 'function'
*  "class::method"                 | ["class", "method"]             | 'static'
*  ["class", "parent::method"]     | ["parent of class", "method"]   | 'static'
*  ["class", "self::method"]       | ["class", "method"]             | 'static'
*  ["class", "method"]             | ["class", "method"]             | 'static'
*  [$object, "parent::method"]     | [$object, "parent::method"]     | 'object'
*  [$object, "self::method"]       | [$object, "method"]             | 'object'
*  [$object, "method"]             | [$object, "method"]             | 'object'
* ---------------------------------+---------------------------------+--------------
*  other callable                  | idem                            | 'unknown'
* ---------------------------------+---------------------------------+--------------
*  not a callable                  | null                            | false
*
* If the "strict" parameter is set to true, additional checks are
* performed, in particular:
*  - when a callable string of the form "class::method" or a callable array
*    of the form ["class", "method"] is given, the method must be a static one,
*  - when a callable array of the form [$object, "method"] is given, the
*    method must be a non-static one.
*
*/
function callableType($callable, $strict = true, callable& $norm = null) {
  if (!
is_callable($callable)) {
    switch (
true) {
      case
is_object($callable):
       
$norm = $callable;
        return
'Closure' === get_class($callable) ? 'closure' : 'invocable';
      case
is_string($callable):
       
$m    = null;
        if (
preg_match('~^(?<class>[a-z_][a-z0-9_]*)::(?<method>[a-z_][a-z0-9_]*)$~i', $callable, $m)) {
          list(
$left, $right) = [$m['class'], $m['method']];
          if (!
$strict || (new \ReflectionMethod($left, $right))->isStatic()) {
           
$norm = [$left, $right];
            return
'static';
          }
        } else {
         
$norm = $callable;
          return
'function';
        }
        break;
      case
is_array($callable):
       
$m = null;
        if (
preg_match('~^(:?(?<reference>self|parent)::)?(?<method>[a-z_][a-z0-9_]*)$~i', $callable[1], $m)) {
          if (
is_string($callable[0])) {
            if (
'parent' === strtolower($m['reference'])) {
              list(
$left, $right) = [get_parent_class($callable[0]), $m['method']];
            } else {
              list(
$left, $right) = [$callable[0], $m['method']];
            }
            if (!
$strict || (new \ReflectionMethod($left, $right))->isStatic()) {
             
$norm = [$left, $right];
              return
'static';
            }
          } else {
            if (
'self' === strtolower($m['reference'])) {
              list(
$left, $right) = [$callable[0], $m['method']];
            } else {
              list(
$left, $right) = $callable;
            }
            if (!
$strict || !(new \ReflectionMethod($left, $right))->isStatic()) {
             
$norm = [$left, $right];
              return
'object';
            }
          }
        }
        break;
    }
   
$norm = $callable;
    return
'unknown';
  }
 
$norm = null;
  return
false;
}

?>

Hope someone else finds it useful.
up
18
bradyn at NOSPAM dot bradynpoulsen dot com
6 years ago
When trying to make a callable from a function name located in a namespace, you MUST give the fully qualified function name (regardless of the current namespace or use statements).

<?php

namespace MyNamespace;

function
doSomethingFancy($arg1)
{
   
// do something...
}

$values = [1, 2, 3];

array_map('doSomethingFancy', $values);
// array_map() expects parameter 1 to be a valid callback, function 'doSomethingFancy' not found or invalid function name

array_map('MyNamespace\doSomethingFancy', $values);
// => [..., ..., ...]
up
3
gulaschsuppe2 at gmail dot com
2 years ago
I tried many possible ways of calling functions by function name directly and assigned to a variable on 3v4l. Not mentioned yet, it is possible to use an array as a caller, at least since PHP 7.1.25. The following script contains all the information I gained:

<?php

// Call function via function name:
    // Basics:
        // A function can also be called by using its string name:
       
function callbackFunc() {
            echo
'Hello World';
        }

       
'callbackFunc'(); // Hello World
                           
        // A function can also be called if its name is assigned to a variable:
           
function callbackFunc() {
                echo
'Hello World';
            }

           
$funcName = 'callbackFunc';
           
$funcName(); // Hello World

    // Static class method:
        // It is also possible to call a public static class method via 'ClassName::functioName' notation:
           
class A {
                public static function
callbackMethod() {
                    echo
"Hello World\n";
                }
            }
           
'A::callbackMethod'(); // Hello World

           
$funcName = 'A::callbackMethod';
           
$funcName(); // Hello World

    // Non static class method:
        // It is also possible to call non static class methods by creating an array which first element is the object the method should be called on and the second element is the non static method to be called. The array can directly be used as a caller:
           
class A {
                private
$prop = "Hello World\n";

                public function
callbackMethod() {
                    echo
$this->prop;
                }
            }

           
$a = new A;
            [
$a, 'callbackMethod']();
           
$funcCallArr = [$a, 'callbackMethod'];
           
$funcCallArr();

       
// Of course this also works inside the class with '$this':
           
class A {
                private function
privCallback() {
                    echo
'Private';
                }

                public function
privCallbackCaller($funcName) {
                    [
$this, $funcName]();
                }
            }

            (new
A)->privCallbackCaller('privCallback'); // Private

?>
up
4
Daniel Klein
4 years ago
You can use "self::method_name", "static::method_name" and "parent::method_name" in callables:

<?php
class StaticCallable {
    public static function
foo($values) {
        return
array_map('self::bar', $values);
    }

    public static function
bar($value) {
        return
"{$value}: 42";
    }

    public static function
baz($values) {
        return
array_map('static::qux', $values);
    }

    public static function
qux($value) {
        return
"{$value}: 123";
    }
}

class
StaticExtension extends StaticCallable {
    public static function
bar($value) {
        return
"{$value}: Marvin the Paranoid Android";
    }

    public static function
qux($value) {
        return
"{$value}: Zaphod Beeblebrox";
    }
}

print_r(StaticCallable::foo([1, 2, 3]));
print_r(StaticExtension::foo([1, 2, 3]));

print_r(StaticCallable::baz([1, 2, 3]));
print_r(StaticExtension::baz([1, 2, 3]));
?>

Results:
Array
(
    [0] => 1: 42
    [1] => 2: 42
    [2] => 3: 42
)
Array
(
    [0] => 1: 42
    [1] => 2: 42
    [2] => 3: 42
)
Array
(
    [0] => 1: 123
    [1] => 2: 123
    [2] => 3: 123
)
Array
(
    [0] => 1: Zaphod Beeblebrox
    [1] => 2: Zaphod Beeblebrox
    [2] => 3: Zaphod Beeblebrox
)

"self::" uses the same class as the called method, "static::" uses the same class as the called class, and "parent::" (not shown) uses the parent class, or generates a warning if there is no parent.
up
3
pawel dot tadeusz dot niedzielski at gmail dot com
6 years ago
@edanschwartz at gmail dot com

You can use ::class property to always indicate the class you're in when using static methods:

<?php
class Foo {
    public static function
doAwesomeThings() {
       
FunctionCaller::callIt(self::class . '::someAwesomeMethod');
    }

    public static function
someAwesomeMethod() {
       
// fantastic code goes here.
   
}
}

class
FunctionCaller {
    public static function
callIt(callable $func) {
       
call_user_func($func);
    }
}

Foo::doAwesomeThings();
?>
up
2
whysteepy at gmail dot com
5 years ago
Another Appearance of Callbacks! Here is one way of them - methods of an instantiated object can be callable and implemented as variable functions without php's default functions that can call user-defined callback functions.

class Test {
    protected $items = array();

    public function __construct()
    {
        $this->items[] = array($this, 'callBackOne');
        $this->items[] = array($this, 'callBackTwo');
    }

    public function callBackOne()
    {
        echo __METHOD__ . ' has been called as a callback.';
    }

    public function callBackTwo()
    {
        echo __METHOD__ . ' has been called as a callback.';
    }   

    public function getItems()
    {
        return $this->items;
    }
}

$o = new Test();
$itemLists = $o->getItems();

foreach ($itemLists as $itemList) {

        // call each one as a variable function
        echo '<pre>';
        print_r($itemList());
        echo '</pre>';
}

// Outputs the following
// Test::callBackOne has been called as a callback.

// Test::callBackTwo has been called as a callback.
up
2
ssi-anik
9 months ago
From the note of https://www.php.net/manual/en/language.types.callable.php#109073
seems like the method name in `call_user_func*` is CASE-INSENSITIVE.
up
-1
chechomancr at hotmail dot com
4 months ago
In PHP >= 8.0 callIt function with optional parameters.
<?php
declare(strict_types = 1);

class
Example {

    public static function
someFunction(string $value, string $a_parameter, int $another_parameter): string
   
{
        
//TODO: Apply the required filter
       
return "$value $a_parameter $another_parameter";
    }

    public static function
callIt(string $callback, ...$parameters): callable
    {
        return static
fn(mixed $value = null) => self::$callback($value, ...$parameters);
    }

}
?>

How to use:
<?php
declare(strict_types = 1);

$args = [
   
'information' => ['filter'  => FILTER_CALLBACK'options' => Example::callIt('someFunction', 'world', 2022)],
];

$unfiltered_data = ['information' => 'Hello'];

$filtered_data = filter_var_array($unfiltered_data, $args);

if(
false === $filtered_data) {
    echo
"Error...", PHP_EOL;
}

echo
var_export($filtered_data, true);
?>

Result: array ( 'information' => 'Hello world 2022' )
up
-2
chris dot rutledge at gmail dot com
3 years ago
Having read this line in the manual above,

"A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed."

I decided to do some testing to see if I could access private methods using the call_user_func methods. Thankfully not, but for completeness here is my test which also covers using static and object contexts

<?php
class foo {
   
    public static
$isInstance = false;
   
    public function
__construct() {
       
self::$isInstance = true;
    }

    public function
bar() {
       
var_dump(self::$isInstance);
        echo
__METHOD__;
    }
   
    private function
baz() {
       
var_dump(self::$isInstance);
        echo
__METHOD__;
    }
   
    public function
qux() {
       
$this->baz();
    }
   
    public function
quux() {
       
self::baz();
    }
}

call_user_func(['foo','bar']);    //fase, foo:bar

call_user_func(['foo','baz']);  //warning, cannot access private method

call_user_func(['foo','quux']); //false, foo::baz

call_user_func(['foo','qux']);  //fatal, Using $this when not in object context

$foo = new foo;

call_user_func([$foo,'bar']);    //true, foo::bar
call_user_func([$foo,'baz']);    //warning, cannot access private method
call_user_func([$foo,'qux']);    //true, foo::baz

call_user_func(['foo','bar']);  //true, foo::bar (static call, yet $isInstance is true)

?>
up
-9
Dan J
4 years ago
You can avoid repeating a long namespace for classes in callable arrays by making use of the "use" operator and the special "::class" constant.

Documentation of use operator:
http://php.net/manual/en/language.namespaces.importing.php

Documentation of ::class constant:
http://php.net/manual/en/language.oop5.constants.php

<?php
// Library file with namespace My\Library\Namespace
require 'MyLibrary.php';

// Alias for SortingClass
use \My\Library\Namespace\SortingClass;

// Callable array referring to SortingClass::SortFunction
$callable = [SortingClass::class, 'SortFunction'];

$values = [3, 1, 2];
usort($values, $callable);

官方地址:https://www.php.net/manual/en/language.types.callable.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3