通过 class 递归调用函数?

Function call through class recursion?

在我的代码中,我有两个 类- 第一个 "Foo" 启动第二个 "Bar"...我想做的是找到一些使用函数的方法和来自父级的变量。

class Bar {
    function __construct() {
        /* 
         * From within this function, how do I access either the returnName() function
         * OR the $this -> name variable from the class above this?
         * The result being:
         */
        $this -> name = parent::returnName();
        $this -> else = parent -> name;
    }
}

class Foo {
    function __construct() {
        $this -> name = 'Fred';
        $this -> var = new Bar();
    }

    function returnName() {
        return $this -> name;
    }
}

$salad = new Foo();

我知道 "parent" 的语法是指 implement 或 extends,但是可以使用这种方法吗?

你可以在Bar

的构造函数中注入$this(Foo class)
<?php
class Bar {
    function __construct($fooClass) {
        /* 
         * From within this function, how do I access either the returnName() function
         * OR the $this -> name variable from the class above this?
         * The result being:
         */
        $this -> name = $fooClass->returnName();
        $this -> else = $fooClass -> name;
    }
}

class Foo {
    function __construct() {
        $this -> name = 'Fred';
        $this -> var = new Bar($this);
    }

    function returnName() {
        return $this -> name;
    }
}

$salad = new Foo();

小心轻放

这不是 100% 干净的解决方案,但可以使用。你的代码应该有很好的文档记录以避免将来混淆。

有一个很酷的函数叫做debug_backtrace()

它为您提供有关为获取此函数而进行的所有调用的信息,包括文件名、调用的行、调用的函数、class 和对象名称以及参数。

以下是您的使用方法:

class Bar {
    function __construct() {

        //get backtrace info
        $trace = debug_backtrace();
        //get the object from the function that called class
        //and call the returnName() function
        $this->name = $trace[1]['object']->returnName();
        echo $this->name;

        //want more info about backtrace? use print_r($trace);
    }
}

class Foo {
    function __construct() {
        $this -> name = 'Fred';
        $this -> var = new Bar();
    }

    function returnName() {
        return $this -> name;
    }
}

$salad = new Foo();

结果:

Fred