PHP Callback Functions

PHP

PHP callback फ़ंक्शन केवल एक फ़ंक्शन है जिसे किसी दूसरी फ़ंक्शन में एक argument के रूप में pass किया जाता है और फिर उसे उस दूसरे फ़ंक्शन के अंदर execute किया जाता है।

callback को लागू करने के कई तरीके हैं, हम उनमें से कुछ को देखेंगे।

Standard PHP Callback Function

PHP में फ़ंक्शन को, call_user_func() फ़ंक्शन का उपयोग करके कॉल किया जा सकता है, जहां पर फ़ंक्शन का नाम एक arguments के रूप में होता है जिसे कॉल किया जाना होता है। यह PHP कॉलबैक फ़ंक्शंस का सबसे सरल प्रकार है।

Example: call_user_func() function
<?php

// Function to print a string
function oneFunction(){
    echo "This is a standard callback";
}

// Standard callback
call_user_func("oneFunction");
?>
Output
This is a standard callback

array_map() function

किसी array में प्रत्येक स्ट्रिंग की लंबाई की गणना करने के लिए, एक कॉलबैक पास किया जाता है array_map() फ़ंक्शन पर।

Example: array_map() function
<?php
function call_function($item){
    return strlen($item);
}

$pcParts = ["Mouse", "Keyboard", "Monitor", "CPU"];
$lengths = array_map("call_function", $pcParts);
print_r($lengths);
?>
Output
Array ( [0] => 5 [1] => 8 [2] => 7 [3] => 3 )

Object method callback

Object methods को call_user_func() का उपयोग करके कॉल किया जा सकता है जहां पर argument एक array है जिसमें object variable होता है और method का नाम को कॉल किया जाता है।

Example: Object method callback
<?php

// Sample class
class MyClass{

    // Function to print a string
    static function oneFunction()
    {
        echo "Hello World";
    }
}

// Class object
$myObj = new MyClass();

// Object method call
call_user_func(array($myObj, 'oneFunction'));
?>
Note: PHP version 7 के शुरुआत से, PHP अज्ञात functions को कॉलबैक फ़ंक्शन के रूप में पास कर सकता है।

PHP Call function के बारे में अधिक जानने के लिए, कृपया देखें https://www.php.net/manual/en/language.types.callable.php

Article By: Brajlal Prasad
Created on: 17 Feb 2023  1046  Views
 Print Article
Report Error

If you want to report an error, or any suggestion please send us an email to [email protected]