Php callback function name

Pass a function name as parameter in a function

Thanks @Jompper It works! Darhazer’s didn’t though.. —edit: Needn’t that detailed 🙂 The first edit explained well. Thanks! You should post that as an answer.

3 Answers 3

Yes, you can. Variable functions are core feature and I’m even not aware which version of PHP they appear for the first time (they exists in PHP 4)

@KoiFish: Just use call_user_fun() . That does exactly the same thing. And if for some reason you want to build a custom function, see demo.

If you want to know all the possibilities, take a look at the callable types documentation

Callback Types

Example #1 Callback function examples

 // An example callback method class MyClass < static function myCallbackMethod() < echo 'Hello World!'; >> // Type 1: Simple callback call_user_func('my_callback_function'); // Type 2: Static class method call call_user_func(array('MyClass', 'myCallbackMethod')); // Type 3: Object method call $obj = new MyClass(); call_user_func(array($obj, 'myCallbackMethod')); // Type 4: Static class method call (As of PHP 5.2.3) call_user_func('MyClass::myCallbackMethod'); // Type 5: Relative static class method call (As of 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 ?> 

Example #2 Callback example using a Closure

; // This is our range of numbers $numbers = range(1, 5); // Use the closure as a callback here to // double the size of each element in our // range $new_numbers = array_map($double, $numbers); print implode(' ', $new_numbers); ?> 

And also, take a look at the variable functions, that other people already told you about

Читайте также:  Javascript eval execute function

Variable functions

Example #1 Variable function example

\n"; > function bar($arg = '') < echo "In bar(); argument was '$arg'.
\n"; > // This is a wrapper function around echo function echoit($string) < echo $string; >$func = 'foo'; $func(); // This calls foo() $func = 'bar'; $func('test'); // This calls bar() $func = 'echoit'; $func('test'); // This calls echoit() ?>

Object methods can also be called with the variable functions syntax.

Example #2 Variable method example

$name(); // This calls the Bar() method > function Bar() < echo "This is Bar"; >> $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable() ?> 

When calling static methods, the function call is stronger than the static property operator:

Example #3 Variable method example with static properties

 > echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope. $variable = "Variable"; Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope. ?> 

Источник

How do I implement a callback in PHP?

The manual uses the terms «callback» and «callable» interchangeably, however, «callback» traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:

$cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod']; // this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error // legacy syntax for PHP 4 $cb3 = array(&$object, 'somePublicMethod'); 

This is a safe way to use callable values in general:

Modern PHP versions allow the first three formats above to be invoked directly as $cb() . call_user_func and call_user_func_array support all the above.

  1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. [‘Vendor\Package\Foo’, ‘method’]
  2. call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb() ;
  3. Objects with an __invoke() method (including anonymous functions) fall under the category «callable» and can be used the same way, but I personally don’t associate these with the legacy «callback» term.
  4. The legacy create_function() creates a global function and returns its name. It’s a wrapper for eval() and anonymous functions should be used instead.

Источник

PHP Callback Functions

A callback function (often referred to as just «callback») is a function which is passed as an argument into another function.

Any existing function can be used as a callback function. To use a function as a callback function, pass a string containing the name of the function as the argument of another function:

Example

Pass a callback to PHP’s array_map() function to calculate the length of every string in an array:

$strings = [«apple», «orange», «banana», «coconut»];
$lengths = array_map(«my_callback», $strings);
print_r($lengths);
?>

Starting with version 7, PHP can pass anonymous functions as callback functions:

Example

Use an anonymous function as a callback for PHP’s array_map() function:

$strings = [«apple», «orange», «banana», «coconut»];
$lengths = array_map( function($item) < return strlen($item); >, $strings);
print_r($lengths);
?>

Callbacks in User Defined Functions

User-defined functions and methods can also take callback functions as arguments. To use callback functions inside a user-defined function or method, call it by adding parentheses to the variable and pass arguments as with normal functions:

Example

Run a callback from a user-defined function:

function ask($str) return $str . «? «;
>

function printFormatted($str, $format) // Calling the $format callback function
echo $format($str);
>

// Pass «exclaim» and «ask» as callback functions to printFormatted()
printFormatted(«Hello world», «exclaim»);
printFormatted(«Hello world», «ask»);
?>

Источник

What is a callback function and how do I use it with OOP

I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions? I guess im wondering why I use this, and what does it do as I have never come across a callback function before!

6 Answers 6

Here’s a basic callback function example:

"; $callbackFunc(); > function thisFuncGetsCalled() < echo "I'm a callback function!
"; > thisFuncTakesACallback( 'thisFuncGetsCalled' ); ?>

You can call a function that has its name stored in a variable like this: $variable().

So, in the above example, we pass the name of the thisFuncGetsCalled function to thisFuncTakesACallback() which then calls the function passed in.

Great and simple answer, thanks. I’ve one question though, what is the minimum required PHP version that has this feature available?

This answer is out-of-date. Today, PHP uses the term ‘callback’ to refer to a specific kind of function. For more information read PHP’s own documentation on the matter: php.net/manual/en/function.call-user-func.php

A callback function will use that function on whatever data is returned by a particular method.

I’m not sure how this particular library works, but it could be something as simple as:

$html = file_get_html('http://example.com'); $html->set_callback('make_bold'); $html->find('#title'); // returns an array function make_bold($results) < // make the first result bold return ''.$results[0].''; > 

ie, The function » make_bold() » will be run on any data found. Again, I’m not sure how this particular library works (ie, what methods the callback function will get called on)

A callback is either a function, an object instance’ method, or a static method on a class. Either way, it’s kind of a function pointer. In some languages, functions are a specific type. So you could assign a function to a variable. These are generally called function oriented languages. A good example is Javascript.

In PHP, a callback can be any of:

$fn = 'foo'; // => foo() $fn = array($obj, 'foo'); // => $obj->foo() $fn = array('Foo', 'bar'); // => Foo::bar() 

You can invoke a callback with the rather verbose function call_user_func .

A callbacks/callable is a simple function(either it is anonymous or named function) that we pass to another function as function parameter which in the result returns that passed function.

function iWillReturnCallback($callBackHere) < return $callBackHere; >function iAmCallBack() < echo "I am returned with the help of another function"; >iWillReturnCallback(iAmCallBack()); //--Output -> I am returned with the help of another function 

Don’t be confused

There are some default functions in php that accepts the name of the callback function as a string in their parameter because of avoiding conflicting between the constant name and function name. So don’t be confused in these kind of things.

With PHP 5.3 , you can now do this:

function doIt($callback) < $callback(); >doIt(function() < // this will be done >); 

Finally, a nice way to do it. A great addition to PHP , because callbacks are awesome.

The aim is to call a function that we want eg: secretCode() but we want to use another function as a helper or service to call it for us:

We have received your command to call your requested function and we are now calling it for you! 
"; // Below is the part where it will call our secretCode()'s function $call(); // And we can print other things after the secretCode()'s function has been executed: echo "[callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day!
"; > function secretCode() < echo "[secretCode]: Hey, this is secretCode function. Your secret code is 12345
"; > callBackServiceCenter( 'secretCode' ); ?>
[callBackServiceCenter]: Hey, this is callBackServiceCenter function We have received your command to call your requested function and we are now calling it for you! [secretCode]: Hey, this is secretCode function. Your secret code is 12345 [callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day! 

Источник

Оцените статью