码迷,mamicode.com
首页 > Web开发 > 详细

php 对象方式传入参数

时间:2018-10-05 15:11:36      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:主机   基本配置   stat   @param   字符   cti   char   库类   erro   

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

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 对象方式传入参数

标签:主机   基本配置   stat   @param   字符   cti   char   库类   erro   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!