PHP:下层类从上层类访问公共函数
考虑以下代码:PHP:下层类从上层类访问公共函数,php,oop,scope,hierarchy,Php,Oop,Scope,Hierarchy,考虑以下代码: class Upper { private $lower; function __construct($passme1, $passme2) { if(!class_exists("Lower")) { include 'path/to/file.php'; } $this->lower = new Lower($passme1, $passme2); } //funct
class Upper {
private $lower;
function __construct($passme1, $passme2) {
if(!class_exists("Lower")) {
include 'path/to/file.php';
}
$this->lower = new Lower($passme1, $passme2);
}
//functions
public function foo() {
//queries database and returns user specific information
}
}
在链接文件中,我有一个较低的类:
class Lower {
function __construct($passme1, $passme2) {
//sort the passed variables out
}
public function bar() {
//trying to access the public function foo of class Upper
}
}
public function bar (Upper $upper) {
$upper->foo();
}
我发现自己需要从class Lower的功能栏中访问class Upper的函数foo
这有可能吗
谢谢你,Joe要从
Lower::bar()
访问Upper::foo()
,必须将$this
变量作为参数传递:
低年级:
class Lower {
function __construct($passme1, $passme2) {
//sort the passed variables out
}
public function bar() {
//trying to access the public function foo of class Upper
}
}
public function bar (Upper $upper) {
$upper->foo();
}
在某种上流社会的方法中:
$this->lower->bar($this);
注意:如果您不需要在
Upper::foo()
中访问$this
,您可能需要将该方法声明为static
,然后在Lower::bar()
中执行以下操作:
关于目的的信息很少,这取决于设计如何解决这个问题谢谢。真是太棒了!