dtkmejg127475 2016-10-17 07:31
浏览 18

如何回显类功能?

Is this possible to echo the class function? I tried this but I'm getting error;

<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条回答 默认 最新

  • doubu7425 2016-10-17 08:17
    关注

    I don't believe you can pass that just as is, but that doesn't mean it can't be achieved. You could write a small function that will parse the input into values you can use to call the desired function. Something like this

    <?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());
        }
    }
    

    I've added a dummy class to show the output, and didn't include any check for existing functions for instance (possible with something like method_exists). You'll need to change that to work with your own class setup and functions.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀