如何在使用变量时创建新的类实例

时间:2011-09-21 15:42:47

标签: php mysql class function instance

很难解释我的意思,所以这里是一个例子。

class mysql {

    public function __construct(){
        //connect to db and select table
    }
    ....
}


class Index Extends perent_class {

    public $mysql;

    public function no_mysql_required(){

        //this function might be called and no mysql is required 

    }

    public function mysql_required(){..}  // this needs mysql. 
    public function mysql_required2(){..} // this needs mysql.
    public function mysql_required3(){..} // this needs mysql.

}


选项1:
$this->mysql = new mysql();
将此添加到需要连接到mysql的所有函数中,但是可以调用其中两个函数,这将创建两个与mysql的连接,这是不好的。

选项2:

if( !is_object($this-mysql) ) $this->mysql = new Mysql();
这只会一次创建一个mysql对象并解决问题,但它会在函数中创建非常重复的代码。创造&调用函数$ this-> start_mysql()也是重复的。

所以我真正想要的是每当我调用$ this-> mysql-> function();即使它还没有创建,在索引perent_class中创建“$ this-> mysql = new Mysql”会自动创建一次,而不是在进行新函数调用时重新创建它。我可能做错了,如果有更好的解决方案,请发布它。

谢谢。

2 个答案:

答案 0 :(得分:1)

您要做的是为mysql类使用单例模式。这样就不会打开不必要的连接。所以它大致看起来像这样

你的mysql类

class Mysql{
    private function __construct(){ } 

    private static $instance;
    .
    .
 public static function singleton(){
        if (!isset(self::$instance)) {
            $c = __CLASS__; 
            self::$instance = new $c;
         }

       return self::$instance;
  }

现在你可以在其他课程中使用它。

$mysql = Mysql::singleton(); 

答案 1 :(得分:0)

如果我理解你的问题,似乎你想要使用'Singleton'设计模式。这允许您只创建一个类的一个实例;尝试创建第二个实例仅返回原始实例。这是代码提取:

<?php

class mysql {
  private static $mysql;

  public $testProperty;

  private function __construct() { } // Declared private so cannot instantiate objects in client code.

  public static function instance() {
    if (!isset(self::$mysql)) {
      self::$mysql = new self();
    }
    return self::$mysql;
   }
 }

?>

通过使用此模式,对mysql::instance();的调用将返回mysql对象的新实例(如果尚未创建)。如果已创建,则将返回相同的实例。因此,您只有一个对象实例。通过多次调用mysql::instance()来测试它:

$instance1 = mysql::instance();
$instance1->testProperty = 'abc';
var_dump($instance1->testProperty);

$instance2 = mysql::instance();
var_dump($instance2->testProperty);