简体   繁体   中英

How to access other classes methods within a class (PHP)

I'm building a PHP OOP MVC Framework for personal use.

I'd like to know if there's a way or the correct implementation of the following:

Being able to call a method from a "subclass" (not extended) to another "subclass". I mean... I have a class that creates new objects for each subclass instead of using inheritance. Let's call it MainClass, and it has 3 "SubClasses" like this

class MainClass {
    public $db;
    public $forms;
    public $pagination;

    function __construct() {
        $this->db = new class_db();
        $this->forms = new class_forms();       
        $this->utils = new class_utils();
    }   
}

And the initialization which is

$MainClass = new MainClass();

I can do for example

$MainClass->utils->show_text("Hello World");

And works fine.

What I'd like to do is... within the $MainClass->utils->test() (Another test method), is to be able to access $MainClass->db without using global or $GLOBALS.

Is there any alternative way of achieving this? To be able to access $MainClass methods and submethods within another submethod (access db from utils and from the main page where MainClass is initialized)? How would it be? I want to be able to access al the submethods, like utils being able to access db and forms method. as well as the pages that are outside MainClass.

Thank you

If utils has to use db , you either have to pass the MainClass instance to utils, so it can call $this->myRefToMain->db , or pass the instance of db itself, so utils can call $this->db . Either way, it cannot (reasonably) crawl up the call stack to find the object that called it.

Object if your class class_utils can exists without MainClass . And its method test() should access some object db of class class_db . This means class_utils depends on class_db and you should inject object of class_db in constructor, for example:

class MainClass {
    public $db;
    public $forms;
    public $pagination;

    function __construct() {
        $this->db = new class_db();
        $this->forms = new class_forms();       
        $this->utils = new class_utils($this->db);
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM