Reputation: 821
I have created function
function do_stuff($text) {
$new_text = nl2br($text);
return $new_text;
}
$result = do_stuff("Hello \n World!");
//returns "Hello <br /> World!"
I want to be able to supply another simple built in PHP function e.g. strtoupper() inside my function somehow, its not just strtoupper() that i need, i need ability to supply different functions into my do_stuff() function.
Say i want to do something like this.
$result = do_stuff("Hello \n World!", "strtolower()");
//returns "Hello <br /> World!"
How would i make this work without creating another function.
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
$sub_function($new_text);
return $new_text;
}
$result = do_stuff("Hello \n World!");
//returns "Hello <br /> World!"
P.S. Just remembered variable variables, and googled, there's actually is Variable functions too, might answer this one myself.
http://php.net/manual/en/functions.variable-functions.php
Upvotes: 0
Views: 77
Reputation: 2160
Callables can be strings, arrays with a specific format, instances of the Closure
class created using the function () {};
-syntax and classes implementing __invoke
directly. You can pass any of these to your function and call them using $myFunction($params)
or call_user_func($myFunction, $params)
.
Additionally to the string examples already given in other answers you may also define a (new) function (closure). This might be especially beneficial if you only need the contained logic in one place and a core function is not suitable. You can also wrap paramters and pass additional values from the defining context that way:
Please be aware that the callable typehint requires php 5.4+
function yourFunction($text, callable $myFunction) { return $myFunction($text); }
$offset = 5;
echo yourFunction('Hello World', function($text) use($offset) {
return substr($text, $offset);
});
Output: http://3v4l.org/CFMrI
Documentation hints to read on:
Upvotes: 1
Reputation: 6381
Looks like you're almost there, just need to leave off the parentheses in the second parameter:
$result = do_stuff("Hello \n World!", "strtolower");
Then this should work after a little cleanup:
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
if ($sub_function) {
$new_text = $sub_function($new_text);
}
return $new_text;
}
Upvotes: 0
Reputation: 79024
You have it in your second example. Just make sure to check that it exists and then assign the return to the string. There is an assumption here about what the function accepts/requires as args and what it returns:
function do_stuff($text, $function='') {
$new_text = nl2br($text);
if(function_exists($function)) {
$new_text = $function($new_text);
}
return $new_text;
}
$result = do_stuff("Hello \n World!", "strtoupper");
Upvotes: 1
Reputation: 33573
You can call a function like this:
$fcn = "strtoupper";
$fcn();
in the same way (as you found out yourself), you can have variable variables:
$a = "b";
$b = 4;
$$a; // 4
Upvotes: 0