PHP   发布时间:2019-11-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP设计模式之工厂模式与单例模式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例讲述了php设计模式之工厂模式与单例模式实现方法。分享给大家供大家参,具体如下:

设计模式简单说应对某类问题而设计的解决方式

工厂模式:

相应的对象

php;"> class factory{ function __construct($Name){ if(file_exists('./'.$name.'.class.php')){ return new $name; }else{ die('not exist'); } } }

单例模式:

val = 20; //clone可以调用__clone()克隆即new出一个新的的对象 //$obj_two = clone $obj_one; $obj_two = instance::geTinstance(); echo $obj_two->val; echo '

'; var_dump($obj_one,$obj_two);

运行结果如下:

int 20 object(instancE)[1] public 'val' => int 20

应用:数据库连接类(database access oject)

3306,'host' => 'localhost','username' => 'root','passWARD' => 'root','dbname' => 'instance','charset' => 'utf8' ); private $link; static $instance; private function __clone(){} private function __construct(){ $this->link = mysql_connect($this->arr['host'],$this->arr['username'],$this->arr['passWARD']) or die(mysql_error()); mysql_SELEct_db($this->arr['dbname']) or die('db error'); mysql_set_charset($this->arr['charset']); } static public function geTinsance(){ if(!isset(mysqldb::$instancE)){ mysqldb::$instance = new self; } return mysqldb::$instance; } public function query($sql){ if($res = mysql_query($sql)){ return $res; }return false; } //fetch one public function get_one($sql){ $res = $this->query($sql); if($result = mysql_fetch_row($res)){ return $result[0]; } } //fetch row public function get_row($sql){ $res = $this->query($sql); if($result = mysql_fetch_assoc($res)){ return $result; } return false; } //fetch all public function get_all($sql){ $res = $this->query($sql); $arr = array(); while($result = mysql_fetch_assoc($res)){ $arr[] = $result; } return $arr; } } $mysql = mysqldb::geTinsance();

更多关于php相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》、《》及《

希望本文所述对大家php程序设计有所帮助。

大佬总结

以上是大佬教程为你收集整理的PHP设计模式之工厂模式与单例模式全部内容,希望文章能够帮你解决PHP设计模式之工厂模式与单例模式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。