它很难解释我的意思,所以在这里举一个例子。如何使用变量创建新的类实例
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();即使尚未创建它,也会自动创建“$ this-> mysql = new Mysql”,并自动创建一次,但不会在创建新函数时重新创建它。我可能会做这个错误,如果有更好的解决方案,我在做什么,请张贴它。
谢谢。