Php 使用变量时如何创建新的类实例
很难解释我的意思,所以这里有一个例子 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. } 类mysql{ 公共函数构造(){ //连接到数据库并选择表 } .... } 类索引扩展了perent_类{ 公帑$mysql; 公共函数无需mysql_(){ //可能会调用此函数,并且不需要mysql } 公共函数mysql_required(){..}//这需要mysql。 公共函数mysql_required2(){..}//这需要mysql。 公共函数mysql_required3(){..}//这需要mysql。 } 选项1:$this->mysql=newmysql();将此添加到所有需要连接到mysql的函数中,但是可以调用其中两个函数,这将创建两个到mysql的连接,这是不好的Php 使用变量时如何创建新的类实例,php,mysql,class,function,instance,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
$this->mysql = new mysql(); 选项2:如果(!is_object($this mysql))$this->mysql=new mysql();这将一次只创建一个mysql对象并解决问题,但它会在函数中创建非常重复的代码。创建和调用一个函数$this->start_mysql()也将是重复的。
所以我真正想要的是每当我调用$this->mysql->function();即使尚未创建,也要在索引perent_类中以某种方式自动创建“$this->mysql=new mysql”,一旦创建,而不是在进行新函数调用时重新创建它。我可能做错了,如果有更好的解决方案,请张贴
谢谢。您要做的是为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();
如果我正确理解了您的问题,那么您似乎想要使用“单例”设计模式。这允许您只创建一个类的实例;尝试创建第二个实例只返回原始实例。下面是代码摘录:
<?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;
}
}
?>
<?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;
}
}
?>
$instance1 = mysql::instance();
$instance1->testProperty = 'abc';
var_dump($instance1->testProperty);
$instance2 = mysql::instance();
var_dump($instance2->testProperty);