简体   繁体   English

如何访问类中的其他类方法(PHP)

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

I'm building a PHP OOP MVC Framework for personal use. 我正在构建一个供个人使用的PHP OOP MVC框架。

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 我们称之为MainClass,它有3个这样的“子类”

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. 我想做的是...在$ MainClass-> utils-> test()(另一种测试方法)中,是能够访问$ MainClass-> db而不使用global或$ 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)? 能够访问另一个子方法中的$ MainClass方法和子方法(从utils和初始化MainClass的主页访问db)? How would it be? 会怎么样 I want to be able to access al the submethods, like utils being able to access db and forms method. 我希望能够访问所有子方法,例如utils能够访问db和Forms方法。 as well as the pages that are outside MainClass. 以及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 . 如果utils必须使用db ,则必须将MainClass实例传递给utils,以便它可以调用$this->myRefToMain->db ,或者传递db本身的实例,因此utils可以调用$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 . 对象,如果你的类class_utils可以不存在MainClass And its method test() should access some object db of class class_db . 其方法test()应该访问类class_db某些对象db This means class_utils depends on class_db and you should inject object of class_db in constructor, for example: 这意味着class_utils依赖于class_db ,您应该在构造函数中注入class_db对象,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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