将数据库对象传递到可多次扩展的类中的简单方法
考虑以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 PHP 的静态属性。
现在该属性将在该对象及其子对象的所有实例之间共享。
You could use PHP's static properties.
Now that property will be shared across all instances of that object and it's children.
查看单例设计模式。您不应该需要使用
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.