简体   繁体   English

使用PHP中的Eval()动态创建函数

[英]Dynamically Create Functions with Eval() in PHP

I'm trying to create functions dynamically with eval() . 我正在尝试使用eval()动态创建函数。 But I get this warning: Notice: Use of undefined constant Any suggestion? 但是我得到了这个警告: Notice: Use of undefined constant任何建议?

$funcs = array('func_a', 'func_b', 'func_c');
foreach($funcs as $func_name) {
    eval( 'function ' . $func_name . '() { 
            mainfunc(' . $func_name . '); 
        }' 
    );  
}

func_a();
func_b();
func_c();

function mainfunc($func_name) {
    echo $func_name . '<br />';
}

Assuming the array $func is an option value stored in a database and I need the function names for a callback function in a separate part of the script. 假设数组$func是存储在数据库中的选项值,我需要在脚本的单独部分中使用回调函数的函数名称。 So creating anonymous functions with create_function() is not what I'm looking for. 因此,使用create_function()创建匿名函数并不是我想要的。

Thanks for your info. 感谢您的信息。

Use better approach than eval(), it is called overloading . 使用比eval()更好的方法,它被称为重载

Example: 例:

class MainFunc {

    public function __call($name, $arguments)
    {
        echo "_call($name)<br>";
    }

    public static function __callStatic($name, $arguments)
    {
        echo "_callStatic($name)<br>";
    }

}

# php >= 5.4.x
(new MainFunc)->func_a();
(new MainFunc)->func_b("param", "param2");
# or php < 5.4
$mainFunc = new MainFunc;
$mainFunc->func_a();
$mainFunc->func_b("param", "param2");

MainFunc::func_a_static();
MainFunc::func_b_static("param", "param2");

Output is: 输出是:

_call(func_a)
_call(func_b)
_callStatic(func_a_static)
_callStatic(func_b_static)

Your eval body needs to read: 您的评估机构需要阅读:

mainfunc(\'' . $func_name . '\'); 

Without the single quotes, eval() makes code that has an unquoted literal--an undefined constant. 如果没有单引号,eval()会生成具有不带引号的文字的代码 - 未定义的常量。

For those who were wondering what I was talking about, here is the sample WordPress plugin which demonstrates how dynamic function creation comes handy. 对于那些想知道我在说什么的人来说,这里是一个示例WordPress插件,它演示了如何动态创建动态函数。

/* Plugin Name: Sample Action Hooks with Dynamic Functions */

// assuming this is an option retrieved from the database
$oActions = array(  'a' => array('interval' => 10, 'value' => 'hi'),
                    'b' => array('interval' => 30, 'value' => 'hello'),
                    'c' => array('interval' => 60, 'value' => 'bye')
            );  

add_action('init', LoadEvents);
function LoadEvents() {
    global $oActions;
    foreach($oActions as $strActionName => $array) {
        eval( 'function ' . $strActionName . '() { 
                    SampleEvents(\'' . $strActionName . '\'); 
                }' 
        );  
        add_action('sampletask_' . md5($strActionName), $strActionName);
        if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
            wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));                  
    }
}
function SampleEvents($strActionName) {
    global $oActions;
    // just log for a demo
    $file = __DIR__ . '/log.html';
    $current = date('l jS \of F Y h:i:s A') . ': ' . $strActionName . ', ' . $oActions[$strActionName]['value'] . '<br />' . PHP_EOL;
    file_put_contents($file, $current, FILE_APPEND);    
    wp_schedule_single_event(time() + $oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
}

And the same functionality could be achieved with __call() . 使用__call()可以实现相同的功能。

/* Plugin Name: Sample Action Hooks */

add_action('init', create_function( '', '$oSampleEvents = new SampleEvents;' ));
class SampleEvents {
    public $oActions = array(   'a' => array('interval' => 10, 'value' => 'hi'),
                                'b' => array('interval' => 30, 'value' => 'hello'),
                                'c' => array('interval' => 60, 'value' => 'bye')
                        );
    function __construct() {                
        foreach($this->oActions as $strActionName => $arrAction) {
            add_action('sampletask_' . md5($strActionName), array(&$this, $strActionName));
            if (!wp_next_scheduled( 'sampletask_' . md5($strActionName)))
                wp_schedule_single_event(time() + $this->oActions[$strActionName]['interval'], 'sampletask_' . md5($strActionName));
        }
    }
    function __call($strMethodName, $arguments) {
        // just log for a demo
        $file = __DIR__ . '/log.html';
        $current = date('l jS \of F Y h:i:s A') . ': ' . $strMethodName . ', ' . $this->oActions[$strMethodName]['value'] . '<br />' . PHP_EOL;
        file_put_contents($file, $current, FILE_APPEND);    
        wp_schedule_single_event(time() + $this->oActions[$strMethodName]['interval'], 'sampletask_' . md5($strMethodName));
    }
}

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

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