将数据库对象传递到可多次扩展的类中的简单方法

发布于 2024-09-17 06:59:31 字数 889 浏览 5 评论 0原文

考虑以下 PHP 代码:

<?php
require_once("myDBclass.php");
class a {
    private $tablename;
    private $column;
    function __construct($tableName, $column) {
        $this->tableName = $tablename;
        $this->column = $column;        
    }

    function insert() {
        global $db;
        $db->query("INSERT INTO ".$this->tableName." (".$this->column.") VALUES (1)");  
    }       
}

class x extends a {
    function __construct() {
        parent::construct("x", "colX"); 
    }
}

class y extends a {
    function __construct() {
        parent::construct("y", "colY"); 
    }
}
?>

我有一个在另一个文件中实例化的 $db 对象,但希望以某种方式将其传递到类 a 的函数中,而不是每次在类“a”中定义一个新函数时都使用 global 关键字。

我知道我可以通过在实例化类 X 和 Y 时传递 DB 对象,然后以这种方式将其传递给类 A 来做到这一点(就像我目前对表名和列所做的那样),但是我永远不知道我可能会扩展类多少次A 认为一定还有另一种更简单的方法。

有谁知道我可以考虑实现此目标的更好解决方案?

提前致谢

Consider the following PHP code:

<?php
require_once("myDBclass.php");
class a {
    private $tablename;
    private $column;
    function __construct($tableName, $column) {
        $this->tableName = $tablename;
        $this->column = $column;        
    }

    function insert() {
        global $db;
        $db->query("INSERT INTO ".$this->tableName." (".$this->column.") VALUES (1)");  
    }       
}

class x extends a {
    function __construct() {
        parent::construct("x", "colX"); 
    }
}

class y extends a {
    function __construct() {
        parent::construct("y", "colY"); 
    }
}
?>

I have my $db object that is instantiated in another file but wish to somehow pass this into class a's functions without using the global keyword everytime i define a new function in class "a".

I know i can do this by passing the DB object when instantiating class X and Y, then passing it through to class A that way (like im currently doing with the tablename and column), however i never know how many times i might extend class A and thought that there must be another easier way somehow.

Does anybody know of a better solution that i could consider to achieve this?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城半夏 2024-09-24 06:59:31

您可以使用 PHP 的静态属性

class A {
    static $db;
    public static function setDB($db) {
        self::$db = $db;
    }
}

现在该属性将在该对象及其子对象的所有实例之间共享。

You could use PHP's static properties.

class A {
    static $db;
    public static function setDB($db) {
        self::$db = $db;
    }
}

Now that property will be shared across all instances of that object and it's children.

花辞树 2024-09-24 06:59:31

查看单例设计模式。您不应该需要使用 globals,因为您似乎知道这是没有必要的。

Look into the Singleton Design Pattern. You should not have the need to use globals, as you seem to know it is not necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文