我有一些变量和函数,需要在不同的类中使用。因此,我将所有定义(变量/函数)放在某个类中:
class common_functions() {
function __construct() {
$this->define_variables();
$this->connect_to_database();
echo "EXEC";
}
function define_variables() {
$this->var1 = "foo";
$this->var2 = "bar";
}
function connect_to_database() {
mysql_connect(...)
}
function do_something() {
//...
}
}它是所有其他类的父类:
class orders extends common_functions {
private $order_item;
function __construct() {
parent::__construct()
$order_item = new item();
}
function show_something() {
echo $order_item->get_something()*$this->var1;
}
}
class item extends common_functions {
pivate $some_number;
function __construct() {
parent::__construct()
$this->number = 123;
}
function get_something() {
return $this->var2*$this->var1*$this->number;
}
}
class some_other_class extends common_functions {
function __construct() {
parent::__construct()
}
// ..
}但是,在执行时
$o = new order();
$o->show_something();输出为
EXEC
EXEC因为common_functions类被调用了两次。特别是mysql-connection需要多次建立,效率非常低。
我需要的是一些技术,这样来自common_functions的所有函数和变量(以及数据库连接)对于所有类都是可用的,而不会有connect_to_database()多次执行的缺点。一些想法?
发布于 2013-11-25 01:32:43
如果我是你,我会重新设计我的实现。为什么?因为在我看来,some_other_class和item 都不是 common_functions。然而,它们都有common_functions。因此,我只创建该类的一个实例,并将其传递给构造函数。
如下所示:
class Item {
private $common_functions;
public function __construct($common_functions) {
$this->common_functions = $common_functions;
}
}
class Order {
private $common_functions;
public function __construct($common_functions) {
$this->common_functions = $common_functions;
}
}现在发生的情况是,item和some_other_class对象都有一个我们注入到common_functions中的依赖项。这显然意味着您必须将一些值传递给common_functions中的方法,但考虑到您从不继承common_functions中获得的好处,这是一个非常小的代价,比如只有一个db连接。
继承很酷,但在实践中它并没有被广泛使用。组合对象通常比继承一堆东西要好得多。在设计OO类时,总是要考虑对象关系是is a还是has a关系。
因此,您可以使用上面的orders构造函数示例执行以下操作:
class orders {
private $common_functions;
public function __construct($common_functions) {
$this->common_functions = $common_functions;
$order_item = new Item($common_functions);
}
}这样,item和order将共享同一个common_functions对象。
发布于 2013-11-25 02:07:15
最初在父类中分配一个静态null变量,并检查它是否为null。
类common_functions {
private static $dbInstance = null;
function __construct() {
if(self::$dbInstance == null) {
self::$dbInstance = $this->connect_to_database();
}} ...
在$this->connect_to_ database ()中返回数据库连接处理程序或NULL值以外的任何值;
https://stackoverflow.com/questions/20177459
复制相似问题