PHP不像JavaScript那样冒泡,所以你的$class2是未定义的:
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well […] Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
换句话说,PHP中只有全局范围和函数/方法范围.因此,要么将$class2实例作为协作者传递给方法
class class1
{
function func1($class2) {
$class2->func3();
}
}
$class1 = new class1();
$class2 = new class2();
$class1->func1($class2);
或者通过构造函数注入它:
class class1
{
private $class2;
public function __construct(Class2 $class2)
{
$this->class2 = $class2;
}
function func1()
{
$this->class2->func3();
}
}
$class2 = new class2();
$class1 = new class1($class2);
$class1->func1();