如何回显类功能?

时间:2016-10-17 07:31:08

标签: php

这可以回应类功能吗? 我试过这个,但是我收到了错误;

<input type="text" name="query">
ex. empid('1');

    <?php
    include 'class/class.sample.php';
    $sampleObj = new sample();
    $function = $_POST['query']; //ex empid('1');
    echo $drObj->$function;
    ?>

1 个答案:

答案 0 :(得分:0)

我不相信你可以按原样通过,但这并不意味着它无法实现。您可以编写一个小函数,将输入解析为可用于调用所需函数的值。像这样的东西

<?php
// I've commented your include because it doesn't benefit this example
//include 'class/class.sample.php';
$sampleObj = new sample();
//$function = $_POST['query']; //ex empid('1');

// set input hardcoded for the benefit of this example
$output = fetchFunction("empid('1','2','3')");
call_user_func_array(array($sampleObj, $output['function']), $output['parameters']);

/**
 * Use this function to parse input like "empid('1','2')"
 * to array('function'=>'empid',parameters=>array(1,2))
 * This can be used in a call_user_func_array
 *
 * @param $input
 * @return array
 */
function fetchFunction($input){
    // match inside () to get the parameters
    preg_match('/(?<=\()(.+)(?=\))/is', $input, $parameters);

    return array(
        'parameters' => explode(',', str_replace(array('\'','"'),'',$parameters[0])),
        'function' => substr($input,0,strpos($input,'('))
    );
}


class sample{
    public function empid($id){
        print_r(func_get_args());
    }
}

我添加了一个虚拟类来显示输出,并且没有包含对现有函数的任何检查(例如method_exists之类的可能)。您需要更改它以使用您自己的类设置和功能。