Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:下层类从上层类访问公共函数_Php_Oop_Scope_Hierarchy - Fatal编程技术网

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()
中执行以下操作:


关于目的的信息很少,这取决于设计如何解决这个问题谢谢。真是太棒了!