分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

php 对象方式传入参数

发布时间:2023-09-06 02:17责任编辑:董明明关键词:暂无标签

类是单例模式,对象方式传入参数,如果参数过多是,使用形参容易混乱

class Object { ???/** ????* 基本配置信息 ????* @var array ????*/ ???private $config = array( ???????‘dbms‘=> ???‘mysql‘, ???//数据库类型 ???????‘host‘=> ???‘localhost‘,//数据库主机名 ???????‘dbName‘=> ?‘back‘, ???//使用的数据库 ???????‘user‘=> ???‘root‘, ????//数据库连接用户名 ???????‘pass‘=> ???‘‘, ?????????//对应的密码 ???????‘char‘=> ???‘utf8‘, ?// 字符集 ???????‘long_conn‘=>false, // 是否是长连接 ???); ???// 数据连接 dsn ???private $dsn=""; ???private static $_instance = null; ???/** 初始化对象 ????* @parem $config ?array ????* */ ???private function __construct($config = array()) ???{ ???????$this->config ??= ??array_merge($this->config,$config); ???????$this->str_dsn(); ???} ???//公有化获取实例方法 ???public static function getInstance(){ ???????if (!(self::$_instance instanceof Singleton)){ ???????????self::$_instance = new Object(); ???????} ???????return self::$_instance; ???} ???//私有化克隆方法 ???private function __clone(){ ???} ???// 拼接dsn 连接字符串 ???private function str_dsn() ???{ ???????return ?$this->dsn="$this->dbms:host=$this->host;dbname=$this->dbName;charset=$this->char"; ???} ???// pdo 连接 ???public ?function conn() ???{ ???????if($this->config[‘long_conn‘]==true) ???????{ ???????????$this->config[‘long_conn‘]=array(PDO::ATTR_PERSISTENT => true); ???????}else ???????{ ???????????$this->config[‘long_conn‘]=array(); ???????} ???????try {
       // 实例化 PDO 对象 ???????????$pdo = new PDO($this->dsn, $this->config[‘user‘], $this->config[‘pass‘],$this->config[‘long_conn‘]); ????????????echo ‘对象:‘; ???????????var_dump($pdo); ???????????echo "<br/>"; ???????????echo ‘参数 user 值: ‘.$this->user; ???????} catch (PDOException $e) { ???????????die ("Error!: " . $e->getMessage() . "<br/>"); ???????} ???} ???/** ????* 使用 $this->name 获取配置 ????* @param ?string $name 配置名称 ????* @return multitype ???配置值 ????*/ ???public function __get($name) ???{ ???????return $this->config[$name]; ???} ???public function __set($name,$value) ???{ ???????if(isset($this->config[$name])) ???????{ ???????????$this->config[$name] = $value; ???????} ???} ???public function __isset($name) ???{ ???????return isset($this->config[$name]); ???}}

 调用示例

$singleton=Object::getInstance();$singleton->pass="admin";$singleton->conn();echo "<br/>";$singleton->conn();

 页面显示结果

对象:object(PDO)#2 (0) { } 参数 user 值: root对象:object(PDO)#2 (0) { } 参数 user 值: root

php 对象方式传入参数

原文地址:https://www.cnblogs.com/xuey/p/9744665.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved