Send string to function php

In PHP, How to call a function interpolated in string?

If you’re calling a method of some class, you can use normal variable expansion. For example:

 > $t = new thingie(); echo "thingie says: sayHello()>"; 

Note that the braces around the call are required.

By wrapping the global functions you want to support in an object of methods, you can control the footprint of exposure to bugs and security leaks. I think you’d be hard-pressed to find an easier way to /safely/ offer such power. Your wrapper methods can even perform additional validation/restriction if needed.

$str = "abcdefg".foo()."hijklmnopqrstuvwxyz"; 

It will call function during string creation.

function foo() < return 'Hi'; >$my_foo = 'foo'; echo ""; 

This is a great «trick.» You can even pass parameters or other variables to it, ie. echo «» or echo «» — especially useful when building SQL queries with many escaped values.

$str="abcdefg foo() hijklmopqrst"; function foo() $replaced = preg_replace_callback("~([a-z]+)\(\)~", function ($m)< return $m[1](); >, $str); 
$replaced == 'abcdefg bar hijklmopqrst'; 

This will allow any lower-case letters as function name. If you need any other symbols, add them to the pattern, i.e. [a-zA-Z_] .

Be VERY careful which functions you allow to be called. You should at least check if $m[1] contains a whitelisted function to not allow remote code injection attacks.

$allowedFunctions = array("foo", "bar" /*, . */); $replaced = preg_replace_callback("~([a-z]+)\(\)~", function ($m) use ($allowedFunctions) < if (!in_array($m[1], $allowedFunctions)) return $m[0]; // Don't replace and maybe add some errors. return $m[1](); >, $str); 

Testrun on «abcdefg foo() bat() hijklmopqrst» outputs «abcdefg bar bat() hijklmopqrst» .

Читайте также:  Вся таблица спецсимволов html

Optimisation for whitelisting approach (building pattern dynamically from allowed function names, i.e. (foo|bar) .

$allowedFunctions = array("foo", "bar"); $replaced = preg_replace_callback("~(".implode("|",$allowedFunctions).")\(\)~", function ($m) < return $m[1](); >, $str); 
$foo = foo(); $str = "abcdefg hijklmopqrst"; 

Short answer

No. There is no native construct to do exactly that.

A simple concatenation may be better. Maybe uglier but more efficient for the PHP parser.

Long answer

If you really need to get arbitrary expressions being evaluated from a double-quoted string, you can implement this workaround, speculating on a feature called variable-functions:

; // Happy hacking echo "Today is <$_( date( 'Y-m-d' ) )>and the max function returns <$_( max( 1, 2, 3 ) )>. <$_( str_repeat( ' arrh', 3 ) )>!"; 
Today is 2018-02-07 and the max function returns 3. arrh arrh arrh! 

The example is not limited to date() , max() and str_repeat() : you can surely define your own functions like foo() and just call them, as long as they return a valid string.

In short this example creates a simple variable. It has a very short name: just an underscore. So, the variable is really called $_ . This variable, to be honest, it’s a function and, to be honest, it just returns what you express in the first argument. This is syntax sugar for you, since functions are not easily expanded as-is inside a string. Instead, variables are expanded easily. That’s it.

I wonder if PHP will ever introduce a native feature to do that (note: I’ve written this note in 2018).

Limitations

Note that, even in this way, the functions are expanded when you define the string. I really cannot guess your needs, but if you need to expand the function later, and not during string definition, you probably need to adopt something more advanced, like a parser. There are many, especially suitable for text templates. But that is outside the scope of this answer I guess.

Feel free to comment / suggest other approaches to expand functions inside a string or just improve your question to share more context about your need.

Источник

calling php function from string (with parameters)

i’d like to run a php-function dynamically by using this string: do_lightbox(‘image1.jpg’, ‘picture 1’) i’ve parsed the string like this:

$exe = "do_lightbox"; $pars = "'image1.jpg', 'picture 1'"; 
$rc = call_user_func($exe, $pars); 

Is there a particular reason as to why you would want to do this, it can cause security issues but it just means that you are writing more lines of code for the same effect. You could change the parameters passed to the function so that they were dynamically loaded (like you want).

6 Answers 6

I think this is what you’re after:

$exe = "do_lightbox"; $pars = array('image1.jpg', 'picture 1'); $rc = call_user_func_array($exe, $pars); 

$pars must be an array with parameters in it. Should be : array(‘image1.jpg’, ‘picture 1’) but with your method, it is : array(«‘image1.jpg'», » ‘picture 1′») which isn’t what you are looking for.

This is an example of how call_user_func() works:

function myfunc($p1,$p2) < echo "first: $p1, second: $p2\n"; >$a1="someval"; $a2="someotherval"; call_user_func("myfunc",$a1,$a2); 

The difference here from previous examples it that you don’t have to pass each argument in a single array. Also, you can parse an array of delimited strings and do the same thing:

function myfunc($p1,$p2) < echo "first: $p1, second: $p2\n"; >$a="someval, someotherval"; $e=explode(", ",$a); $a1=$e[0]; $a2=$e[1]; call_user_func("myfunc",$a1,$a2); 

Источник

How to call a function with a parameter as string in php?

I am looking for something similar to the solution here >> Call function from string stored in a variable, however with one difference : I would like to pass a parameter as well. For example :

 function foo($myvar) < >$function = 'foo'; $values = Array('myvar'=>1, 'myvar2'=>2); if(function_exists($function)) < // call the function using $function, // and pass the value $values -- aka $function($values) >

Any workable solution would be greatly appreciated. Ideally, I would like to use it with classes as follows :

 class bar < function foo($myvar) < >> $function = 'foo'; $values = Array('myvar'=>1, 'myvar2'=>2); if(function_exists($function)) < // call the function using $function, // and pass the value $values -- aka $bar::$function($values) >

It’s not a problem — My question is how can i pass a variable to a function where the function name is stored in a variable. Calling the function directly is not the issue. If you look at the SO link i added, it gives an answer for how to call a function in a string, but not if i wish to pass a variable to that function as well. — so it’s only 50% of the solution i need

3 Answers 3

You can call a function on an object passing params, using variables, as follows:

$myBar = new bar(); // usually class names have uppercase first letters though $myClassname = 'bar'; call_user_func(array($myBar, $function), $values); // method on object call_user_func(array($myClassname, $function), $values); // class (static) method call_user_func($myClassname.'::'.$function); // PHP 5.2.3 and higher // if you had another function $function2 whose args were a list of parameters instead of an array: call_user_func($myBar, $function2, $param1, $param2, $param3); 

can the class itself be called this way as well ? for example, in your example, the class is known and is static — but something like $foo = ‘bar’; $mybar = new $foo; ? or more specifically calling it statically like $foo::$myfunction($params) so all parts can be dynamic

🙂 . I have a follow up question coming . hehe. slightly more complex, but on topic with this — basically, I am writing an event class (so I can raiseevents from other functions/classes/etc). PHP doesn’t seem to have any real event based system.

Источник

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