首页 > 解决方案 > 从字符串调用 PHP 函数,其中字符串是类成员并且函数全局存在

问题描述

我目前正在开发一个项目,其中 $_SERVER["PATH_INFO"] 被格式化,然后用于调用全局定义的函数。本质上,下面的函数可以正常工作:当我在 index.php 中调用 URIHandle() 并在浏览器中加载“index.php/hello”时,会调用全局定义的函数“hello”。

  function URIHandle(){
    $uri = $_SERVER["PATH_INFO"];
    $uri = ltrim($uri,"/");
    $uri = rtrim($uri,"/"); 
    try{
        if(isset($uri))
            echo $uri();
        else
            echo UserHome();
    } catch(Exception $e){
        http_response_code(404); 
    }
}

我希望它适合我的其余代码,因此将其包装在一个类中:

class URIHandler{
    function __construct(){
        $this->uri = $_SERVER["PATH_INFO"];
        $this->Prepare();
    }

    function Prepare(){
        $this->uri = ltrim($this->uri,"/");
        $this->uri = rtrim($this->uri,"/");
    }

    public function Handle(){
        try{
            if(isset($this->uri)){
                echo $this->uri();
            }
            else
                echo UserHome();
        } catch(Exception $e){
            http_response_code(404);
        }
    }
}

如果我实例化此类并调用 Handle(),则不会调用全局定义的方法“hello”。就我而言,这两个功能在功能上应该是相同的。

标签: php

解决方案


一个干净的方法是使用该call_user_func函数。

class URIHandler{
    function __construct(){
        $this->uri = $_SERVER["PATH_INFO"];
        $this->Prepare();
    }

    function Prepare(){
        $this->uri = ltrim($this->uri,"/");
        $this->uri = rtrim($this->uri,"/");
    }

    public function Handle(){
        try{
            if(isset($this->uri)){
                echo call_user_func($this->uri);
            }
            else
                echo UserHome();
        } catch(Exception $e){
            http_response_code(404);
        }
    }
}

还值得注意的是,trim将从给定字符串的开头和结尾删除指定的字符。

$this->uri = ltrim($this->uri,"/");
$this->uri = rtrim($this->uri,"/");

// or

$this->uri = trim($this->uri, '/');

推荐阅读