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
Related
I have a string variable
$worker_name = "video_convert"
I want to write a function with the name like the following
function video_convert(){
}
How can I do this in PHP? I tried
function eval($worker_name){
}
or
eval($worker_name) = function(){
}
But, it seems like it is not the correct way to do it in PHP.
You can do it as
$worker_name = 'video_convert';
$$worker_name = function() {
echo 'hi';
};
$$worker_name();
You could use call_user_func :
$worker_name ="video_convert"
function video_convert($text){
echo "Hello $text\n";
}
call_user_func($worker_name, 'World');
OR you could use the way you tried:
$worker_name = 'video_convert';
function video_convert(){
echo __METHOD__;
}
$worker_name();
OR like this:
$worker_name = function($text)
{
echo 'Anonymous function call '.$text
};
$worker_name('Hello');
PHP is flexible.
You can do somewhat like as
$worker_name = "video_convert";
function video_convert(){
echo "I've called a function using variable";
}
$worker_name();
If you want to use eval() function then use it by below way:-
$worker_name = "video_convert()";
function video_convert(){
echo "Called";
}
eval("$worker_name;");
I have a function variable like this...
$aName = "My Name";
The function need to pass in like this:
$sayHelloFunction = function sayHello($aName){
echo($aName);
}
Than, I have a method that responsible for execute the sayHelloFunction:
runningFunction($sayHelloFunction($aName));
in the runningFunction, it will have some condition to execute the function, but when I pass the "$sayHelloFunction($aName)" to runningFunction, it execute automatically, but I would like to pass the variable $aName as well, how can I achieve it? Thank you.
runningFunction($sayHelloFunction, $aName);
Simples.
You will have to pass the arguments separately. However, you could wrap them in an array so that you can pass them to runningFunction as a single argument, like this:
$printFunction = function($args) {
print $args['lastname'].', '.$args['firstname'];
};
function runningFunction($f, $a) {
$f($a);
}
$firstname = 'Bob';
$lastname = 'Smith';
$functionArguments = array(
'firstname' => $firstname,
'lastname' => $lastname
);
runningFunction($printFunction, $functionArguments);
If you want your dynamic functions to get "proper" arguments, then I see no way around something like this:
function runningFunction($f, $a) {
switch(count($a)) {
0: $f(); break;
1: $f($a[0]); break;
2: $f($a[0], $a[1]); break;
3: $f($a[0], $a[1], $a[2]); break;
// and so on
}
}
Pass the parameters as an array, and then use call_user_func_array() to call your function.
This way your runningFunction() will be absolutely abstract (as you requested), it can call any type of function, it's your responsibility to pass the right number of parameters.
function runningFunction ($callback, $parameters=array()) {
call_user_func_array($callback, $parameters);
}
runningFunction($sayHelloFunction, array($aName));
call_user_func_array()
as xconspirisist suggested pass $aName as a seperate parameter to the function.
Details on Variable Functions can be found on the PHP site.
Use an anonymous function when calling runningFunction
function runningFunction($func) {
$func();
}
runningFunction(function() {
$sayHelloFunction($aName));
// You can do more function calls here...
});
I just simply want to create a function name with a string value.
Something like this:
$ns = 'test';
function $ns.'_this'(){}
test_this();
It of course throws an error.
I've tried with:
function {$ns}.'_this'
function {$ns.'_this'}
but no luck.
Any thoughts?
You can use create_function to create a function from provided string.
Example (php.net)
<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>
This is not possible. If all you want to do is, to prefix all functions with some common string, maybe you want to use namespaces?
namespace foo {
function bar() {}
function rab() {}
function abr() {}
}
// access from global namespace is as follows:
namespace {
foo\bar(); foo\rab(); foo\abr();
}
file with function (somefile.php)
function outputFunctionCode($function_name)
{?>
function <?php echo $function_name ?>()
{
//your code
}
<?php }
file with code which "declares" the function:
ob_start();
include("somefile.php");
outputFunctionCode("myDynamicFunction");
$contents = ob_get_contents();
ob_end_clean();
$file = fopen("somefile2.php", "w");
fwrite($file,$contents);
fclose($file);
include("somefile2.php");
It is ugly, but then again, it is an extremely bad idea to declare functions with dynamic names.
using "eval" is not a good practice, but that may serve the purpose similar to your requirements sometimes.
<?php
$ns = 'test';
$funcName = $ns.'_this';
eval("function $funcName(){ echo 1;}");
test_this();
?>
Is this what you are looking for?
<?php
function foo($a) { print 'foo called'.$a; }
$myfunctionNameStr = 'foo';
$myfunctionNameStr(2);
?>
Cause i don't think that you can dynamically construct a function declaration. You can decide at 'runtime' the value of the $myfunctionNameStr though.
What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.
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.