I have the following piece of code
copy($source, $target);
I also use
move_uploaded_file($source, $target);
To prevent code reuse, I want to pass copy and move_uploaded_file in via a variable.
If my variable is $var = "copy";
, simply putting $var($source, $target);
, doesn't seem to work.
Are there any special characters that must surround $var
?
Thanks.
The correct syntax is $var
(variable functions), so your code should work.
But please don't do that, just write the code in a straightforward and readable manner. There are legitimate use cases for this technique, but this is not one of them.
You can use the PHP function call_user_func().
You can use call_user_func
to do this.
$result = call_user_func($functionToCall, $source, $target)
Documentation: PHP: call_user_func
You want to look at Variable Functions which goes on to explain how to do that.
function foo() {
echo "In foo()<br />
";
}
$bar = 'foo';
$bar(); //this calls foo()
This can also be done on both object methods and static methods.
Object Methods
class Foo
{
function MyFunction()
{
//code here
}
}
$foo = new Foo();
$funcName = "MyFunction";
$foo->$funcName();
Static Methods
class Bar
{
static function MyStaticFunction()
{
//code here
}
}
$funcName = "MyStaticFunction";
Bar::$funcName();
While maybe not the case in your situation, when dealing with functions dynamically like this, it is important to check whether the function actually exists and/or is callable.
Alternatively to using Variable Functions, you can use call_user_func
which will call the function based on the string name and with provided parameters.
as far as i know your code should work
here is the link for your refrence