php - 从字符串调用 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”。就我而言,这两个功能在功能上应该是相同的。
解决方案
一个干净的方法是使用该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, '/');
推荐阅读
- javascript - catch 分支缺少覆盖
- android - 横幅 - 是否有内置视图?
- r - ¿ 如何创建一个动态 FOR 循环,该循环根据按因子级别分组的数据集打印条形图?
- beautifulsoup - BeautifulSoup findAll() 找不到所有,无论我使用哪个解析器
- c# - Devenv.com 在 sln 文件中没有看到一个 csproj(通过 Azure DevOps 构建的命令行)
- katalon-studio - Katalon Studio - 从一个项目中引用单独的 Git 存储库
- css - 无法找到引导类
- r - 在十六进制代码中获取给定颜色的 n 个阴影
- java - Rest API 线程安全
- html - CSS - 试图让内容按比例缩小以适应较小的屏幕