我目前正在处理一个项目,该项目中格式化了$ _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”。就我而言,这两个功能在功能上应该相同。
答案 0 :(得分:1)
一种干净的方法是使用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, '/');