为什么无法识别全局变量?

Why a global variable isn't recognized?

我想调用在代码中某处定义的变量。我使用 global 关键字,但似乎无法识别变量。当我在本地设置变量时,它工作得很好。 (它是 $title 变量,它接收某个对象的静态函数的值)

这个有效:

class Book {
    public function represent() {
        $titles = Title::all_by_id();
        $title = $titles[$this->title_id];
        return $title->represent().'_'.$this->id;
    }
}

这个没有:

$titles = Title::all_by_id();

在另一个文件中

 class Book {
     public function represent(){
        global $titles;
        $title = $titles[$this->title_id];
        return $title->represent().'_'.$this->id;
     }
 }

发送错误:

PHP Fatal error: Call to a member function represent() on a non-object in

这里可能存在哪些问题?

我解决了,问题是我将 $titles 变量设置在与 Book class 定义的主上下文不同的子上下文中

当我改变我定义那个变量的地方时,我解决了这个问题,我把它放在主上下文中。