Π—Π²ΠΎΡ€ΠΎΡ‚Π½Ρ– Π²ΠΈΠΊΠ»ΠΈΠΊΠΈ (Callbacks / Callables)

ΠŸΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 5.4, Π·Π²ΠΎΡ€ΠΎΡ‚Π½Ρ– Π²ΠΈΠΊΠ»ΠΈΠΊΠΈ ΠΌΠΎΠΆΡƒΡ‚ΡŒ ΠΏΠΎΠ·Π½Π°Ρ‡Π°Ρ‚ΠΈΡΡŒ Ρ‡Π΅Ρ€Π΅Π· Ρ‚ΠΈΠΏ callable, Ρ‰ΠΎ ΠΎΠ·Π½Π°Ρ‡Π°Ρ” - ΠΏΡ€ΠΈΠ΄Π°Ρ‚Π½ΠΈΠΉ для Π²ΠΈΠΊΠ»ΠΈΠΊΠ°. Π’ Π΄Π°Π½Ρ–ΠΉ Π΄ΠΎΠΊΡƒΠΌΠ΅Π½Ρ‚Π°Ρ†Ρ–Ρ— Ρ‚ΠΈΠΏ callback Π²ΠΆΠΈΠ²Π°ΡŽΡ‚ΡŒ Π· Ρ‚Ρ–Ρ”ΡŽ ΠΆ ΠΌΠ΅Ρ‚ΠΎΡŽ.

ДСякі Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ—, Π½Π°ΠΏΡ€ΠΈΠΊΠ»Π°Π΄, call_user_func() Π°Π±ΠΎ usort() ΠΏΡ€ΠΈΠΉΠΌΠ°ΡŽΡ‚ΡŒ Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½Ρ– користувачСм callback-Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ— Π² якості ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π°. Callback-Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ— ΠΌΠΎΠΆΡƒΡ‚ΡŒ Π±ΡƒΡ‚ΠΈ Π½Π΅ лишС простими функціями, Π°Π»Π΅ Ρ‚Π°ΠΊΠΎΠΆ Ρ– ΠΌΠ΅Ρ‚ΠΎΠ΄Π°ΠΌΠΈ ΠΎΠ±'Ρ”ΠΊΡ‚Ρ–Π², Π²ΠΊΠ»ΡŽΡ‡Π°ΡŽΡ‡ΠΈ статичні ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΈ класів.

ΠŸΠ΅Ρ€Π΅Π΄Π°Ρ‡Π° Π·Π²ΠΎΡ€ΠΎΡ‚Π½Ρ–Ρ… Π²ΠΈΠΊΠ»ΠΈΠΊΡ–Π²

Π―ΠΊ Π°Ρ€Π³ΡƒΠΌΠ΅Π½Ρ‚, функція PHP ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ”Ρ‚ΡŒΡΡ ΠΏΠΎ Ρ–ΠΌΠ΅Π½Ρ– Ρƒ вигляді рядка. Π‘ΡƒΠ΄ΡŒ-яка Π²Π±ΡƒΠ΄ΠΎΠ²Π°Π½Π° Π°Π±ΠΎ Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½Π° користувачСм функція ΠΌΠΎΠΆΠ΅ ΠΏΠ΅Ρ€Π΅Π΄Π°Π²Π°Ρ‚ΠΈΡΡŒ Ρ‚Π°ΠΊΠΈΠΌ Ρ‡ΠΈΠ½ΠΎΠΌ, Π·Π° Π²ΠΈΠΊΠ»ΡŽΡ‡Π΅Π½Π½ΡΠΌ ΠΌΠΎΠ²Π½ΠΈΡ… конструкцій, Ρ‚Π°ΠΊΠΈΡ… як: array(), echo, empty(), eval(), exit(), isset(), list(), print Π°Π±ΠΎ unset().

ΠœΠ΅Ρ‚ΠΎΠ΄, Π²ΠΆΠ΅ створСного ΠΎΠ±'Ρ”ΠΊΡ‚Π°, ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ”Ρ‚ΡŒΡΡ Π² масиві, Π΄Π΅ сам ΠΎΠ±'Ρ”ΠΊΡ‚ ΠΌΠ°Ρ” індСкс 0, Π° ΠΉΠΎΠ³ΠΎ ΠΌΠ΅Ρ‚ΠΎΠ΄ - індСкс 1.

Π’Π°ΠΊΠΎΠΆ Π² масиві ΠΌΠΎΠΆΠ½Π° ΠΏΠ΅Ρ€Π΅Π΄Π°Π²Π°Ρ‚ΠΈ статичний ΠΌΠ΅Ρ‚ΠΎΠ΄ класа, ΠΊΠΎΠ»ΠΈ Π² індСксі 0, Π·Π°ΠΌΡ–ΡΡ‚ΡŒ ΠΎΠ±'Ρ”ΠΊΡ‚Π°, ΠΉΠ΄Π΅ Π½Π°Π·Π²Π° класа. ΠŸΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 5.2.3, ΠΌΠ΅Ρ‚ΠΎΠ΄ Π²ΠΆΠ΅ ΠΌΠΎΠΆΠ½Π° ΠΏΠ΅Ρ€Π΅Π΄Π°Π²Π°Ρ‚ΠΈ Π² Ρ„ΠΎΡ€ΠΌΠ°Ρ‚Ρ– 'ClassName::methodName'.

ΠžΠΊΡ€Ρ–ΠΌ Π·Π°Π³Π°Π»ΡŒΠ½ΠΈΡ… Ρ„ΡƒΠ½ΠΊΡ†Ρ–ΠΉ, Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½ΠΈΡ… користувачСм, anonymous functions (Π°Π½ΠΎΠ½Ρ–ΠΌΠ½Ρ– Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ—) Ρ‚Π°ΠΊΠΎΠΆ ΠΌΠΎΠΆΡƒΡ‚ΡŒ ΠΏΠ΅Ρ€Π΅Π΄Π°Π²Π°Ρ‚ΠΈΡΡŒ Π² якості callback-ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Ρ–Π².

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #1 callback-Ρ„ΡƒΠ½ΠΊΡ†Ρ–ΠΉ

<?php

// ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ callback-Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ—
function my_callback_function() {
echo
'ΠŸΡ€ΠΈΠ²Ρ–Ρ‚, Π‘Π²Ρ–Ρ‚!';
}

// ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ callback-ΠΌΠ΅Ρ‚ΠΎΠ΄Π°
class MyClass {
static function
myCallbackMethod() {
echo
'ΠŸΡ€ΠΈΠ²Ρ–Ρ‚, Π‘Π²Ρ–Ρ‚!';
}
}

// Π’ΠΈΠΏ 1: ΠŸΡ€ΠΎΡΡ‚ΠΈΠΉ callback
call_user_func('my_callback_function');

// Π’ΠΈΠΏ 2: Π’ΠΈΠΊΠ»ΠΈΠΊ статичного ΠΌΠ΅Ρ‚ΠΎΠ΄Π° класа
call_user_func(array('MyClass', 'myCallbackMethod'));

// Π’ΠΈΠΏ 3: Π’ΠΈΠΊΠ»ΠΈΠΊ ΠΌΠ΅Ρ‚ΠΎΠ΄Π° ΠΎΠ±'Ρ”ΠΊΡ‚Π°
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Π’ΠΈΠΏ 4: Π’ΠΈΠΊΠ»ΠΈΠΊ статичного ΠΌΠ΅Ρ‚ΠΎΠ΄Π° класа (ΠŸΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Π’ΠΈΠΏ 5: Π’ΠΈΠΊΠ»ΠΈΠΊ відносного статичного ΠΌΠ΅Ρ‚ΠΎΠ΄Π° (ΠŸΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 5.3.0)
class A {
public static function
who() {
echo
"A\n";
}
}

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

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

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #2 ΠŸΠ΅Ρ€Π΅Π΄Π°Ρ‡Π° Π°Π½ΠΎΠ½Ρ–ΠΌΠ½ΠΎΡ— Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ— Π² якості сallback-ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π°

<?php
// Наша Π°Π½ΠΎΠ½Ρ–ΠΌΠ½Π° функція
$double = function($a) {
return
$a * 2;
};

// Π¦Π΅ наш Π΄Ρ–Π°ΠΏΠ°Π·ΠΎΠ½ Π½ΠΎΠΌΠ΅Ρ€Ρ–Π²
$numbers = range(1, 5);

// Використовуємо Π°Π½ΠΎΠ½Ρ–ΠΌΠ½Ρƒ Ρ„ΡƒΠ½ΠΊΡ†Ρ–ΡŽ як callback-ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ для
// пСрСмноТСння Π½Π° 2 ΠΊΠΎΠΆΠ½ΠΎΠ³ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Π° Π² Π½Π°ΡˆΠΎΠΌΡƒ Π΄Ρ–Π°ΠΏΠ°Π·ΠΎΠ½Ρ–
$new_numbers = array_map($double, $numbers);

print
implode(' ', $new_numbers);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

2 4 6 8 10

ЗауваТСння: Π’ PHP 4, Π½Π΅ΠΎΠ±Ρ…Ρ–Π΄Π½ΠΎ Π±ΡƒΠ»ΠΎ використовувати посилання для створСння callback, який Π²ΠΊΠ°Π·ΡƒΡ” Π½Π° Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΠΈΠΉ ΠΎΠ±'Ρ”ΠΊΡ‚, Π° Π½Π΅ Π½Π° ΠΉΠΎΠ³ΠΎ ΠΊΠΎΠΏΡ–ΡŽ. Для ΡƒΡ‚ΠΎΡ‡Π½Π΅Π½ΡŒ, ΠΏΡ€ΠΎΠ³Π»ΡΠ½ΡŒΡ‚Π΅ ПояснСння Посилань.

ЗауваТСння:

Π—Π²ΠΎΡ€ΠΎΡ‚Π½Ρ– Π²ΠΈΠΊΠ»ΠΈΠΊΠΈ, зарСєстровані Ρ‡Π΅Ρ€Π΅Π· Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ— call_user_func() Ρ– call_user_func_array(), Π½Π΅ Π±ΡƒΠ΄ΡƒΡ‚ΡŒ Π²ΠΈΠΊΠ»ΠΈΠΊΠ°Ρ‚ΠΈΡΡŒ ΠΏΡ€ΠΈ наявності нСспійманих винятків, Π²ΠΈΠΊΠΈΠ½ΡƒΡ‚ΠΈΡ… Π² ΠΏΠΎΠΏΠ΅Ρ€Π΅Π΄Π½Ρ–Ρ… Π·Π²ΠΎΡ€ΠΎΡ‚Π½Ρ–Ρ… Π²ΠΈΠΊΠ»ΠΈΠΊΠ°Ρ….

οΌ‹add a note

User Contributed Notes 12 notes

up
288
andrewbessa at gmail dot com ΒΆ
13 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
211
steve at mrclay dot org ΒΆ
13 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
193
computrius at gmail dot com ΒΆ
12 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
186
Riikka K ΒΆ
11 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
187
edanschwartz at gmail dot com ΒΆ
11 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
178
metamarkers at gmail dot com ΒΆ
13 years ago
you can pass an object as a callable if its class defines the __invoke() magic method..
up
119
mariano dot REMOVE dot perez dot rodriguez at gmail dot com ΒΆ
10 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
13
InvisibleSmiley ΒΆ
5 years 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
23
bradyn at NOSPAM dot bradynpoulsen dot com ΒΆ
10 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
6
gulaschsuppe2 at gmail dot com ΒΆ
6 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
1
chris dot rutledge at gmail dot com ΒΆ
7 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
1
pawel dot tadeusz dot niedzielski at gmail dot com ΒΆ
10 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();
?>