代码之家  ›  专栏  ›  技术社区  ›  joe92

PHP:较低层次结构类从较高层次结构类访问公共函数

  •  0
  • joe92  · 技术社区  · 13 年前

    考虑以下代码:

    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
        }
    }
    

    在链接的文件中,我有一个类Lower:

    class Lower {
        function __construct($passme1, $passme2) {
            //sort the passed variables out
        }
        public function bar() {
            //trying to access the public function foo of class Upper
        }
    }
    

    我发现自己需要从类Lower的函数栏中访问类Upper的函数foo。

    这有可能吗?

    非常感谢。

    1 回复  |  直到 13 年前
        1
  •  2
  •   bwoebi    13 年前

    访问 Upper::foo() 从…起 Lower::bar() 你必须通过 $this 变量作为参数:

    班内较低:

    public function bar (Upper $upper) {
        $upper->foo();
    }
    

    在Upper类的某些方法中:

    $this->lower->bar($this);
    

    附言:如果您不需要访问 $这个 在里面 上::foo() 您可能需要将该方法声明为 static 然后进去 下::bar() :

    Upper::foo(); // calls static method foo of class Upper
    
    推荐文章