PHP: class 函数在一个文件中有效,但在另一个文件中无效

PHP: class function works in one file but not another

我正在使用 PHP 制作 Telegram 机器人。我有 bot.php、filter.php 和 test.php。

我希望我的机器人向用户发送包含 ID 的消息。 我有一个过滤器 class,我的 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 的简单 curl http 请求 API)

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

相反,每当调用 bot 函数时 returns 500 内部服务器错误。

请帮忙。

$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);
}

这在测试中有效,因为您没有更改范围。您需要在

中传递 $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);
    }