views:

51

answers:

6

In the process of automating some code, I am looking to call upon a function based on what a string is.

For example, I have a variable $somevar which is set to the string "This". Now I want to run a function doThis();

So, I was hoping I could write do.$somevar($var,$var2) . I want it to run doThis($var1,$var2).

Is this possible?

A: 

In php you use -> instead of . this will work:

$foo = new someObject;
$somevar = 'function_name';
$foo->$somevar('x');
aviv
I think Roeland was using the . as the string concatenation operator
kibibu
that should be `$foo` ;)
ChrisR
+4  A: 

You can use call_user_func to accomplish this.

call_user_func("do" . $somevar, $var1, $var2);

You can also use is_callable to check for error conditions.

if (is_callable("do" . $somevar)) {
    call_user_func("do" . $somevar, $var1, $var2);
} else {
    echo "Function do" . $somevar . " doesn't exist.";
}
MiffTheFox
As far as i know call_user_func works on any callable function, even built in php functions like strtoupper, sprintf, ...
ChrisR
@ChrisRamakers You're right, thank you for pointing this out.
MiffTheFox
+3  A: 

I don't think you can do it like that, but you could do:

call_user_func('do'. $somevar, $var, $var2);

or

$func = 'do' . $somevar;
$func($var, $var2);
Tom Haigh
+1  A: 

This is perfectly legal in php

$myVar = 'This';

$method = 'do'.$myVar; // = doThis
$class  = new MyClass();
$class->$method($var1, $var2, ...); // executes MyClass->doThis();
ChrisR
+1  A: 
$fname="do$somevar";
$fname();

But you should think twice before using it.

Col. Shrapnel
A: 

check call_user_func or call_user_func_array

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
Martin Sikora