简体   繁体   English

如何使用从字符串变量生成的函数名称调用函数

[英]How do I call a function using a function name generated from a string variable

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". 例如,我有一个变量$somevar ,它被设置为字符串“ This”。 Now I want to run a function doThis(); 现在我要运行一个函数doThis();

So, I was hoping I could write do.$somevar($var,$var2) . 因此,我希望可以编写do.$somevar($var,$var2) I want it to run doThis($var1,$var2) . 我希望它运行doThis($var1,$var2)

Is this possible? 这可能吗?

You can use call_user_func to accomplish this. 您可以使用call_user_func完成此操作。

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

You can also use is_callable to check for error conditions. 您也可以使用is_callable检查错误情况。

if (is_callable("do" . $somevar)) {
    call_user_func("do" . $somevar, $var1, $var2);
} else {
    echo "Function do" . $somevar . " doesn't exist.";
}

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

This is perfectly legal in php 这在php中是完全合法的

$myVar = 'This';

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

But you should think twice before using it. 但是在使用它之前,您应该三思。

In php you use -> instead of . 在php中,请使用->而不是。 this will work: 这将工作:

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

check call_user_func or call_user_func_array 检查call_user_func或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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM