PHP:类函数在一个文件中有效,而在另一个文件中无效

问题描述

我正在使用PHP制作Telegram Bot。我有bot.PHP,filter.PHP和test.PHP

我希望我的机器人将包含ID的消息发送给用户我有一个Filter类,并且在filter.PHP中有一个带有正则表达式模式的函数来检测此ID,并且我正在使用preg_match获取匹配项。

public function getID($string) {
    $pattern = "/e0(\d){6}\b/i";
    preg_match($pattern,$string,$matches);
    return $matches[0];
}

在我的test.PHP中,我使用了该功能,它能够将匹配结果回显给我。

<?PHP
include __DIR__ . './filter.PHP';
$check = new Filter();    
$pattern = "/e0(\d){6}\b/i";
$text = "hi e0000000";
echo "id: ".$check->getID($text);
?>

在我的bot.PHP中,我尝试使用相同的功能来发送消息,但是它不起作用。 (sendMsg函数只是对Telegram Bot API的简单curl http请求)

include __DIR__ . './filter.PHP';
$filter = new Filter();
function handleGoodMessage($chatId,$text) {
  $report = "Message '".$text."' passed the filters.\nID: ".$filter->getID($text);
  sendMsg($chatId,$report);
}

相反,无论何时调用函数,机器人都会返回500 Internal Server Error。

请帮助。

解决方法

$filter在函数内部无法访问。

$filter = new Filter(); //<--- filter is here,in the outer scope
function handleGoodMessage($chatId,$text) {
  $report = "Message '".$text."' passed the filters.\nID: ".$filter->getID($text); 
  
  //this scope is inside the function,$filter does not exist here
  sendMsg($chatId,$report);
}

这在测试中有效,因为您无需更改范围。您需要在{p>中传递$filter

------更新----

我个人将始终依靠注入而不是使用globals,所以我的偏好是重新定义如下函数:

function handleGoodMessage($chatId,$text,$filter) {
      $report = "Message '".$text."' passed the filters.\nID: ".$filter->getID($text); 
      sendMsg($chatId,$report);
    }

我可能(冒着使某些人感到不安的危险)将getID定义为static function,因为它实际上并未交互任何东西,不使用任何成员变量,而只是处理字符串并返回。因此,您可以说

,而不是注入它,或使用global
function handleGoodMessage($chatId,$text) {
      $report = "Message '".$text."' passed the filters.\nID: ".Filter::getID($text); 
      sendMsg($chatId,$report);
    }