PHP 多个 child classes,访问 child class 到 class
PHP multiple child classes, accessing child class to class
我不完全确定这是理解问题还是语法问题。
我正在尝试从同一 parent.
下的其他 child 类 访问 child 类
class TopLevel {
foreach (glob("assets/php/*.php") as $filename) // will get all .php files within plugin directory
{
include $filename;
$temp = explode('/',$filename);
$class_name = str_replace('.php','',$temp[count($temp)-1]); // get the class name
$this->$class_name = new $class_name; // initiating all plugins
}
}
class A extends TopLevel {
$var = 'something';
public function output() {
return $this->var;
}
}
class B extends TopLevel {
// This is where I need help, CAN the child class A be accessed sideways from class B? Obviously they need to be loaded in correct order of dependency.
$this->A->output();
}
我不明白为什么这不起作用。结构不是很好,但它是一个 object 应用程序。
答案是:不能,childclassA不能横着访问。 A和B之间没有直接继承。
答案可能是将 $this->A 类型转换为 B 类型的 object,使用类似于此问题答案中的函数:
How to Cast Objects in PHP
在 B 中创建 class A 的对象,然后调用 A 的方法,因为 A 和 B 之间没有父子关系。
$objOfA = new A();
$objOfA->output();
我不完全确定这是理解问题还是语法问题。 我正在尝试从同一 parent.
下的其他 child 类 访问 child 类 class TopLevel {
foreach (glob("assets/php/*.php") as $filename) // will get all .php files within plugin directory
{
include $filename;
$temp = explode('/',$filename);
$class_name = str_replace('.php','',$temp[count($temp)-1]); // get the class name
$this->$class_name = new $class_name; // initiating all plugins
}
}
class A extends TopLevel {
$var = 'something';
public function output() {
return $this->var;
}
}
class B extends TopLevel {
// This is where I need help, CAN the child class A be accessed sideways from class B? Obviously they need to be loaded in correct order of dependency.
$this->A->output();
}
我不明白为什么这不起作用。结构不是很好,但它是一个 object 应用程序。
答案是:不能,childclassA不能横着访问。 A和B之间没有直接继承。
答案可能是将 $this->A 类型转换为 B 类型的 object,使用类似于此问题答案中的函数:
How to Cast Objects in PHP
在 B 中创建 class A 的对象,然后调用 A 的方法,因为 A 和 B 之间没有父子关系。
$objOfA = new A();
$objOfA->output();