如何从 PHP 中同一文件中的函数访问文件范围内定义的数组


How to access an array that is defined in the file scope from a function in the same file in PHP?

我正在编写一个黑名单单词检查器。我将脚本命名为 blacklist_check.php,如下所示:

<?php
$black_list = [
  'ass',
  'anus',
  /* many others that i skipped here */
];
function is_black_listed ($word) {
  return in_array($word, $black_list);
}
?>

但是当我使用is_black_listed功能时,我总是得到Warning: in_array() expects parameter 2 to be array, null given

我应该将$black_list数组放在函数is_black_listed内吗?我不想这样做,因为当我调用函数时,数组总是会被创建,而不是在我需要(或包含)脚本时只创建一次!

我应该在函数中使用global $black_list is_black_listed吗?

帮助我解决此问题的最佳实践!

不要使用全局变量,它们很难维护,并且会使代码的可读性降低。相反,只需将数组传递给函数:

function is_black_listed ($word, $black_list)

然后用以下命令调用它:

is_black_listed( "bad words!", $black_list);

更好的是,创建一个类来执行此操作,并将数组创建为成员变量:

class WordFilter {
    private $black_list = [ ... ];
    function __construct( $words = array()) {
        // Optionally add dynamic words to the list
        foreach( $words as $word) 
            $black_list[] = $word;
    }
    function is_black_listed( $word) {
        return in_array( $word, $this->black_list);
    }
}
$filter = new WordFilter( array( 'potty', 'mouth'));
$filter->is_black_listed( "bad");