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
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");
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:
http://php.net/manual/en/functions.anonymous.php
http://php.net/manual/en/language.types.callable.php
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
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;
}
Related
How can I get PHP to evaluate a static variable in double quotes?
I want to do something like this:
log("self::$CLASS $METHOD entering");
I've tried all sorts of {} combos to get the variable value of self::$CLASS, but nothing has worked. I've currently settled with string concatenation but it is a pain to type:
log(self::$CLASS . " $METHOD entering");
Sorry, you can't do that. It only works for simple expressions. See here.
Unfortunately there is no way how to do this yet. Example in one of answers here will not work, because {${self::$CLASS}} will not returns content of self::$CLASS, but will returns content of variable with name in self::$CLASS.
Here is an example, which does not returns myvar, but aaa:
$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
Use an anonymous identity function stored in a variable. This way you will have $ immediately after {:
$I = function($v) { return $v; };
$interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(I am using class constants in this example but this will work with static variables too).
I don’t know the answer to your question, but you can show the class name and method using the __METHOD__ magic constant.
<?php
class test {
public $static = 'text';
public $self = __CLASS__;
// static Method
static function author() {
return "Frank Glück";
}
// static variable
static $url = 'https://www.dozent.net';
public function dothis() {
$self = __CLASS__;
echo <<<TEST
{${!${''}=static::author()}} // works
{$self::author()} // works
{$this->self::author()} // works
${!${''}=self::author()} // works
{${$this->self}}::author()}} // don't works
${${self::author()}} // do/don't works but with notice
${#${self::author()}} // works but with # !
TEST;
}
}
$test = 'test'; // this is the trick, put the Classname into a variable
echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;
$test = new test();
$test->dothis();
I know this is an old question but I find it odd that noone has suggested the [sprintf][1] function yet.
say:
<?php
class Foo {
public static $a = 'apple';
}
you would use it with:
echo sprintf( '$a value is %s', Foo::$a );
so on your example its:
log(
sprintf ( ' %s $METHOD entering', self::$CLASS )
);
//define below
function EXPR($v) { return $v; }
$E = EXPR;
//now you can use it in string
echo "hello - three is equal to $E(1+2)";
Just live with the concatenation. You'd be surprised how inefficient variable interpolation in strings can be.
And while this could fall under the umbrella of pre-optimization or micro-optimization, I just don't think you actually gain any elegance in this example.
Personally, if I'm gonna make a tiny optimization of one or the other, and my choices are "faster" and "easier to type" - I'm gonna choose "faster". Because you only type it a few times, but it's probably going to execute thousands of times.
Yes this can be done:
log("{${self::$CLASS}} $METHOD entering");
This does not work
$check["pattern"] = "/correct/";
$callback = "function ($m) { return ucfirst($m[0]);}";
echo preg_replace_callback($check["pattern"],$callback,"correct" );
output: correct
This works
$check["pattern"] = "/correct/";
echo preg_replace_callback($check["pattern"],function ($m) { return ucfirst($m[0]);},"correct" );
output: Correct
Why, and how to make it work with the function stored inside a var? :)
Why would you want to do that? I see no reason to store the function inside a variable, to be honest. Nevertheless, if you really want to do this, take a look at create_function:
<?php
$check["pattern"] = "/correct/";
$callback = create_function('$m', 'return ucfirst($m[0]);');
echo preg_replace_callback( $check['pattern'], $callback, "correct" );
// Output: "Correct"
If you do a var_dump on $callback = "function ($m) { return ucfirst($m[0]);}"; the result is a string. In the working situation you pass a Closure (anonymous function) as callback.
The manual is clear: a Closure is allowed, if you pass a string, it must be the name of a function.
I am trying to do something like this:
//function name
$str = 'bla()';
//make function with string as name
function $str{
echo 'yey';
}
//Call the function by string name
bla();
You could use eval() to attempt this task. But I really do NOT suggest it:
// name of the function
$str = 'bla';
// php code you want to execute inside
$inside = '';
eval("
function $str() { $inside }
");
Or you could also use an anonymous function:
$name = function() {
// code
};
// execution
$name();
Als if you are just trying to call a dynamic function just use call_user_func() like this:
// name of the function
$str = 'bla';
// paramters to the function
$param = array();
call_user_func($str, $param);
But I think you are doing something wrong. This kind of "hacks" are sign of bad application architecture.
References
eval()
call_user_func()
Anonymous functions
I'll suggest you, not to use like this. But if still you want to do this,
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
Check here
And you are required to use PHP 5.3
Whenever a function completes, it RETURNS a value. If no value is set to be returned, 0 is returned.
If you would like to be able to do as you have asked, you could do the following:
function blah($string="Blah"){
return($string);
}
echo blah("Banana"); //echo's Banana
echo blah(); //echo's Blah
$str = blah("Apple"); //Sets $str to Apple
I'm sure there's a very easy explanation for this. What is the difference between this:
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
... and this (and what are the benefits?):
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');
Always use the actual function name when you know it.
call_user_func is for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.
Although you can call variable function names this way:
function printIt($str) { print($str); }
$funcname = 'printIt';
$funcname('Hello world!');
there are cases where you don't know how many arguments you're passing. Consider the following:
function someFunc() {
$args = func_get_args();
// do something
}
call_user_func_array('someFunc',array('one','two','three'));
It's also handy for calling static and object methods, respectively:
call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);
the call_user_func option is there so you can do things like:
$dynamicFunctionName = "barber";
call_user_func($dynamicFunctionName, 'mushroom');
where the dynamicFunctionName string could be more exciting and generated at run-time. You shouldn't use call_user_func unless you have to, because it is slower.
With PHP 7 you can use the nicer variable-function syntax everywhere. It works with static/instance functions, and it can take an array of parameters. More info at https://trowski.com/2015/06/20/php-callable-paradox
$ret = $callable(...$params);
I imagine it is useful for calling a function that you don't know the name of in advance...
Something like:
switch($value):
{
case 7:
$func = 'run';
break;
default:
$func = 'stop';
break;
}
call_user_func($func, 'stuff');
There are no benefits to call it like that, the word user mean it is for multiple user, it is useful to create modification without editing in core engine.
it used by wordpress to call user function in plugins
<?php
/* main.php */
require("core.php");
require("my_plugin.php");
the_content(); // "Hello I live in Tasikmalaya"
...
<?php
/* core.php */
$listFunc = array();
$content = "Hello I live in ###";
function add_filter($fName, $funct)
{
global $listFunc;
$listFunc[$fName] = $funct;
}
function apply_filter($funct, $content)
{
global $listFunc;
foreach ($listFunc as $key => $value)
{
if ($key == $funct and is_callable($listFunc[$key]))
{
$content = call_user_func($listFunc[$key], $content);
}
}
echo $content;
}
function the_content()
{
global $content;
$content = apply_filter('the_content', $content);
echo $content;
}
....
<?php
/* my_plugin.php */
function changeMyLocation($content){
return str_replace('###', 'Tasikmalaya', $content);
}
add_filter('the_content', 'changeMyLocation');
in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.
When using namespaces, call_user_func() is the only way to run a function you don't know the name of beforehand, for example:
$function = '\Utilities\SearchTools::getCurrency';
call_user_func($function,'USA');
If all your functions were in the same namespace, then it wouldn't be such an issue, as you could use something like this:
$function = 'getCurrency';
$function('USA');
Edit:
Following #Jannis saying that I'm wrong I did a little more testing, and wasn't having much luck:
<?php
namespace Foo {
class Bar {
public static function getBar() {
return 'Bar';
}
}
echo "<h1>Bar: ".\Foo\Bar::getBar()."</h1>";
// outputs 'Bar: Bar'
$function = '\Foo\Bar::getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()'
$function = '\Foo\Bar\getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()'
}
You can see the output results here: https://3v4l.org/iBERh it seems the second method works for PHP 7 onwards, but not PHP 5.6.
How can I get PHP to evaluate a static variable in double quotes?
I want to do something like this:
log("self::$CLASS $METHOD entering");
I've tried all sorts of {} combos to get the variable value of self::$CLASS, but nothing has worked. I've currently settled with string concatenation but it is a pain to type:
log(self::$CLASS . " $METHOD entering");
Sorry, you can't do that. It only works for simple expressions. See here.
Unfortunately there is no way how to do this yet. Example in one of answers here will not work, because {${self::$CLASS}} will not returns content of self::$CLASS, but will returns content of variable with name in self::$CLASS.
Here is an example, which does not returns myvar, but aaa:
$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
Use an anonymous identity function stored in a variable. This way you will have $ immediately after {:
$I = function($v) { return $v; };
$interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(I am using class constants in this example but this will work with static variables too).
I don’t know the answer to your question, but you can show the class name and method using the __METHOD__ magic constant.
<?php
class test {
public $static = 'text';
public $self = __CLASS__;
// static Method
static function author() {
return "Frank Glück";
}
// static variable
static $url = 'https://www.dozent.net';
public function dothis() {
$self = __CLASS__;
echo <<<TEST
{${!${''}=static::author()}} // works
{$self::author()} // works
{$this->self::author()} // works
${!${''}=self::author()} // works
{${$this->self}}::author()}} // don't works
${${self::author()}} // do/don't works but with notice
${#${self::author()}} // works but with # !
TEST;
}
}
$test = 'test'; // this is the trick, put the Classname into a variable
echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;
$test = new test();
$test->dothis();
I know this is an old question but I find it odd that noone has suggested the [sprintf][1] function yet.
say:
<?php
class Foo {
public static $a = 'apple';
}
you would use it with:
echo sprintf( '$a value is %s', Foo::$a );
so on your example its:
log(
sprintf ( ' %s $METHOD entering', self::$CLASS )
);
//define below
function EXPR($v) { return $v; }
$E = EXPR;
//now you can use it in string
echo "hello - three is equal to $E(1+2)";
Just live with the concatenation. You'd be surprised how inefficient variable interpolation in strings can be.
And while this could fall under the umbrella of pre-optimization or micro-optimization, I just don't think you actually gain any elegance in this example.
Personally, if I'm gonna make a tiny optimization of one or the other, and my choices are "faster" and "easier to type" - I'm gonna choose "faster". Because you only type it a few times, but it's probably going to execute thousands of times.
Yes this can be done:
log("{${self::$CLASS}} $METHOD entering");