子方法是否不能访问父方法';s变量


Does a child method not have access to a parent method's variables?

它不是一个子方法,但它是在我的类Paginate中的另一个方法内部调用的方法。

当我尝试运行这个:

public function paginate() {
    // Other stuff here 
    for ($i = $pageMin; (($i <= $pageMax) && ($i <= $this->arrayLength)); $i++) {
    $this->build(); // The important bit! 
    }
    // Other stuff here 
}
public function build() {
    echo $array[$i]['name'];
}

在为我的build()方法调用echo的行上,我被告知$i is undefined。为什么会这样?在另一个方法内部调用的方法是否不从父方法继承变量?从build()的角度来看,$i不是相对全球化的吗?

我该如何解决此问题?当我在paginate()内部调用$i时,是否必须将其作为参数传递给build()?这看起来不太干净。替代方案?

它们在不同的范围内。

你必须用一个参数来传递它。

$this->build($i); 

--

public function build($i) {
    echo $array[$i]['name'];
}