PHP:class函数在一个文件中工作,但在另一个文件中不工作

PHP:class函数在一个文件中工作,但在另一个文件中不工作,php,regex,telegram,Php,Regex,Telegram,我正在用PHP制作一个电报机器人。我有bot.php、filter.php和test.php 我希望我的机器人向用户发送包含ID的消息。 我有一个Filter类,我的Filter.php中有一个带有regex模式的函数来检测这个id,我使用preg_match来获得匹配 public function getID($string) { $pattern = "/e0(\d){6}\b/i"; preg_match($pattern, $string, $mat

我正在用PHP制作一个电报机器人。我有bot.php、filter.php和test.php

我希望我的机器人向用户发送包含ID的消息。 我有一个Filter类,我的Filter.php中有一个带有regex模式的函数来检测这个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都会返回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);
}
我可能会(冒着让一些人不安的风险)将
getID
定义为一个
静态函数
,因为它没有真正交互任何东西,没有使用任何成员变量,只是处理一个字符串并返回它。因此,与其注射它,或者使用
global
,不如说

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

$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);
}
我可能会(冒着让一些人不安的风险)将
getID
定义为一个
静态函数
,因为它没有真正交互任何东西,没有使用任何成员变量,只是处理一个字符串并返回它。因此,与其注射它,或者使用
global
,不如说

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

所以我需要添加
global$filter
函数内部?@Jerryl我不建议使用
global
,使用globals通常是设计模式不好的标志。我已经为您扩展了我的答案,但我建议您对Scope进行更多的研究,因此我需要添加
global$filter
函数内部?@Jerryl我不建议使用
global
,使用globals通常是设计模式不好的标志。我已经为您扩展了我的答案,但我建议您对范围做更多的研究