从字符串调用PHP函数,其中字符串是类成员,函数全局存在
我目前正在从事一个项目,其中$\u SERVER[“PATH\u INFO”]被格式化,然后用于调用全局定义的函数。基本上,下面的函数工作正常:当我在index.php中调用URIHandle()并在浏览器中加载“index.php/hello”时,会调用全局定义的函数“hello”从字符串调用PHP函数,其中字符串是类成员,函数全局存在,php,Php,我目前正在从事一个项目,其中$\u SERVER[“PATH\u INFO”]被格式化,然后用于调用全局定义的函数。基本上,下面的函数工作正常:当我在index.php中调用URIHandle()并在浏览器中加载“index.php/hello”时,会调用全局定义的函数“hello” function URIHandle(){ $uri = $_SERVER["PATH_INFO"]; $uri = ltrim($uri,"/"); $uri = rtrim($uri
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”。就我而言,这两个函数在功能上应该是相同的。一个干净的方法是使用函数
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);
}
}
}
还值得注意的是,将从给定字符串的开头和结尾删除指定字符
$this->uri = ltrim($this->uri,"/");
$this->uri = rtrim($this->uri,"/");
// or
$this->uri = trim($this->uri, '/');
echo$this->uri()代码>它不是一个方法,所以它应该是echo$this->uri代码>谢谢iDontDownVote,但是如果我有一个函数(函数hello),然后我分配一个字符串var($strello=“hello”),然后调用$strello(),就会调用函数hello。接受的答案使用函数call_user_func,从类内调用时,该函数似乎具有预期效果。