Вызов функции через рекурсию класса?


В моем коде есть два класса-первый " 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" относится либо к реализации, либо к расширению, но возможно ли использовать этот вид метода?

2 2

2 ответа:

Вы можете ввести $this (класс Foo) в конструктор Bar

<?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 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();

Результат:

Фред