1

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?

1
  • are the range of possibilities for $somevar known and limited or unknown and unlimited? Commented Apr 7, 2010 at 6:24

6 Answers 6

4

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.";
}
Sign up to request clarification or add additional context in comments.

2 Comments

As far as i know call_user_func works on any callable function, even built in php functions like strtoupper, sprintf, ...
@ChrisRamakers You're right, thank you for pointing this out.
3

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);

Comments

1

This is perfectly legal in php

$myVar = 'This';

$method = 'do'.$myVar; // = doThis
$class  = new MyClass();
$class->$method($var1, $var2, ...); // executes MyClass->doThis();

Comments

1
$fname="do$somevar";
$fname();

But you should think twice before using it.

Comments

0

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

Comments

0

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

$foo = new someObject;
$somevar = 'function_name';
$foo->$somevar('x');

1 Comment

I think Roeland was using the . as the string concatenation operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.