Implement callback functions in PHP

Create one or more callbackfunctions and execute them using different built-in methods, user-defined functions and static classes in PHP.

[Create a function in PHP callbackand call_user_funcexecute it using

We create a function named testFunction()and callbackuse call_user_func()the method to execute it by passing the function name as a string to the method.

example:

<?php
    function testFunction() {
    
    
        echo "Testing Callback \n";
    }
    // Standard callback
    call_user_func('testFunction');
?>

Output:

Testing Callback

[Create a function in PHP callbackand array_mapexecute it using method]

We use array_mapthe method to execute callbackthe function. This will execute the method using array_map()the corresponding data passed to the function.

example:

<?php
    function length_callback($item) {
    
    
      return strlen($item);
    }
    $strings = ["Kevin Amayi", "Programmer", "Nairobi", "Data Science"];
    $lengths = array_map("length_callback", $strings);
    print_r($lengths);
?>

Output:

Array ( [0] => 11 [1] => 10 [2] => 7 [3] => 12 )

[Implement multiple callback functions in PHP and execute them using user-defined functions]

We will use testCallBacks()a user-defined function named to execute two functions named nameand , bypassing the user-defined function with the name of the function as a string.agecallback

example:

<?php
function name($str) {
    
    
  return $str . " Kevin";
}

function age($str) {
    
    
  return $str . " Kevin 23 ";
}

function testCallBacks($str, $format) {
    
    
  // Calling the $format callback function
  echo $format($str)."<br>";
}

// Pass "name" and "age" as callback functions to testCallBacks()
testCallBacks(" Hello", "name");
testCallBacks(" Hello", "age");
?>

Output:

Hello Kevin
Hello Kevin 23

static[Use classes and call_user_funcimplement staticmethods as functions in PHP callback]

We will staticcreate two staticclasses using the method and execute call_user_func()them as using the method callbacks.

<?php
    // Sample Person class
    class Person {
    
    
          static function walking() {
    
    
              echo "I am moving my feet <br>";
          }
      }
    //child class extends the parent Person class
    class Student extends Person {
    
    
      static function walking() {
    
    
            echo "student is moving his/her feet <br>";
        }
    }
    // Parent class Static method callbacks
    call_user_func(array('Person', 'walking'));
    call_user_func('Person::walking');

    // Child class Static method callback
    call_user_func(array('Student', 'Student::walking'));
?>

Output:

I am moving my feet
I am moving my feet
student is moving his/her feet

Guess you like

Origin blog.csdn.net/weixin_50251467/article/details/131777084