PHP编程进阶:模拟方法重载、对象遍历与MySql单例封装

10 篇文章 1 订阅

前言

PHP的广阔开发领域中,掌握高级特性和设计模式是每位开发者不断追求的目标。本文精心挑选了三个核心话题——模拟方法重载、对象遍历及MySql单例封装,旨在为您呈现一场PHP进阶的盛宴。通过探索模拟方法重载的巧妙实现,您将学会如何灵活应对PHP的局限性;对象遍历的深入讲解,则帮助您更好地理解和操作对象;而MySql单例封装的实践,更是提升数据库连接管理效率的关键。这些内容不仅丰富了您的PHP知识体系,也为您在实际项目开发中提供了宝贵的经验和技巧。无论您是初涉PHP的新手,还是寻求突破的老手,本文都将引领您向更高层次的编程技能迈进。

1、模拟方法重载

1.1 通过魔术方法模拟方法重载

<?php
    class Math {
        // 魔术方法当调用的类中没有调用的方法时会自动执行__call魔术方法
        public function __call($fn_name, $fn_args) {
            $sum=0;
            foreach($fn_args as $v) {
                $sum+=$v;
            }
            // implode为数组连接方法以逗号形式连接数组中的每一项
            echo implode(',', $fn_args).'的和是:'.$sum,'<br/>';
            // print_r($fn_args);
        }
    }

    $math=new Math();
    $math->calla(10,20);
    $math->calla(10,20,30);
    $math->calla(10,20,30,40);

?>

效果:
在这里插入图片描述

2、遍历对象

例:

<?php
    class Student {
        public $name='tom';
        protected $sex='男';
        private $age=22;
        public function show() {
            foreach($this as $k=>$v) {
                echo "${k}-${v}<br/>";
            }
        }
    }
    
    $stu=new Student;
    foreach($stu as $k=>$v) {
        echo "${k}-${v}<br/>";
    }
    echo '<hr/>';
    $stu->show();
?>

效果:
在这里插入图片描述
结论:

遍历到当前位置所能访问到的属性。

3、封装MySql的单例

3.1 分析

1、实现单例
2、连接数据库
3、对数据进行操作

3.2 步骤

第一步:实现单例

<?php
    class MySQLDB {
        private static $instance;
        private function __construct() {

        }
        private function __clone() {

        }
        public static function getInstance() {
            if (!self::$instance instanceof self) {
                self::$instance = new self();
            }
            return self::$instance;
        }
    }

    // 测试
    $db = MySQLDB::getInstance();

    var_dump($db);
?>

注意: A instanceof B,表示A是否是B的类型,返回bool值
效果:
在这里插入图片描述

第二步:初始化参数

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
            
            
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => 'root'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);

    var_dump($db);
?>

效果:
在这里插入图片描述

第三步:连接数据库

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            $this->initConnect();
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
        }
        // 连接数据库
        private function initConnect() {
            $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
            if (mysqli_connect_error()) {
                echo '数据库连接失败<br/>';
                echo '错误信息:'.mysqli_connect_error().'<br/>';
                exit;
            }
            mysqli_set_charset($this->link, $this->charset);
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => 'root'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);

    var_dump($db);
?>

效果:
在这里插入图片描述

第四步:操作数据

1.执行增、删、改操作
改:

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            $this->initConnect();
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
        }
        // 连接数据库
        private function initConnect() {
            $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
            if (mysqli_connect_error()) {
                echo '数据库连接失败<br/>';
                echo '错误信息:'.mysqli_connect_error().'<br/>';
                exit;
            }
            mysqli_set_charset($this->link, $this->charset);
        }
        // 执行数据库的增、删、改、查
        private function execute($sql) {
           if (!$rs=mysqli_query($this->link, $sql)) {
               echo 'SQL语句执行失败<br/>';
               echo '错误信息:'.mysqli_error($this->link),'<br/>';
               echo '错误码:'.mysqli_error($this->link),'<br/>';
               echo '错误的SQL语句:'.$sql,'<br/>';
           }
           else {
                return $rs;
           }
        }
        /**
         * 执行增、删、改
         * @return bool 成功返回true,失败返回false
         */
        public function exec($sql) {
            $key=substr($sql, 0, 6);
            if (in_array($key, array('insert', 'update', 'delete'))) {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            }
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => '123456'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);
    // $db->exec('select * from news'); // 非法访问
    $db->exec("update news set title='Justin' where id=1");
?>

效果:
在这里插入图片描述
增:

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            $this->initConnect();
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
        }
        // 连接数据库
        private function initConnect() {
            $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
            if (mysqli_connect_error()) {
                echo '数据库连接失败<br/>';
                echo '错误信息:'.mysqli_connect_error().'<br/>';
                exit;
            }
            mysqli_set_charset($this->link, $this->charset);
        }
        // 执行数据库的增、删、改、查
        private function execute($sql) {
           if (!$rs=mysqli_query($this->link, $sql)) {
               echo 'SQL语句执行失败<br/>';
               echo '错误信息:'.mysqli_error($this->link),'<br/>';
               echo '错误码:'.mysqli_error($this->link),'<br/>';
               echo '错误的SQL语句:'.$sql,'<br/>';
               exit;
           }
           else {
                return $rs;
           }
        }
        /**
         * 执行增、删、改
         * @return bool 成功返回true,失败返回false
         */
        public function exec($sql) {
            $key=substr($sql, 0, 6);
            if (in_array($key, array('insert', 'update', 'delete'))) {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            }
        }
        // 获取自动增长的编号
        public function getLastInsertId () {
            return mysqli_insert_id($this->link);
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => '123456'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);
    // $db->exec('select * from news'); // 非法访问
    // 更新
    // $db->exec("update news set title='Justin' where id=1");
    // 插入成功
    if ($db->exec("insert into news values (null, 'aa', 'bb', unix_timestamp())")) {
        echo '编号是:'.$db->getLastInsertId();
    }

?>

效果:
在这里插入图片描述
在这里插入图片描述
查:

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            $this->initConnect();
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
        }
        // 连接数据库
        private function initConnect() {
            $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
            if (mysqli_connect_error()) {
                echo '数据库连接失败<br/>';
                echo '错误信息:'.mysqli_connect_error().'<br/>';
                exit;
            }
            mysqli_set_charset($this->link, $this->charset);
        }
        // 执行数据库的增、删、改、查
        private function execute($sql) {
           if (!$rs=mysqli_query($this->link, $sql)) {
               echo 'SQL语句执行失败<br/>';
               echo '错误信息:'.mysqli_error($this->link),'<br/>';
               echo '错误码:'.mysqli_error($this->link),'<br/>';
               echo '错误的SQL语句:'.$sql,'<br/>';
               exit;
           }
           else {
                return $rs;
           }
        }
        /**
         * 执行增、删、改
         * @return bool 成功返回true,失败返回false
         */
        public function exec($sql) {
            $key=substr($sql, 0, 6);
            if (in_array($key, array('insert', 'update', 'delete'))) {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            }
        }
        // 获取自动增长的编号
        public function getLastInsertId () {
            return mysqli_insert_id($this->link);
        }
        // 查询语句
        private function query($sql) {
            if (substr($sql, 0, 6) == 'select' || substr($sql, 0, 4) == 'show' || substr($sql, 0, 4) == 'desc') {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            } 
        }
        /**
         * 执行查询语句,返回二维数组
         * @$sql string 查询sql语句
         * @$type string assoc|num|both
         */
        public function fetchAll($sql, $type='assoc') {
            $rs = $this->query($sql);
            $type=$this->getType($type);
            return mysqli_fetch_all($rs, $type);
        }
        // 获取匹配类型
        private function getType($type) {
            switch($type) {
                // case 'assoc':
                //     return MYSQLI_ASSOC;
                case 'num':
                    return MYSQLI_NUM;
                case 'both':
                    return MYSQLI_BOTH;
                default:
                    return MYSQLI_ASSOC;
            } 
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => '123456'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);
    // 查询
    // $list = $db->fetchAll('select * from news', 'assoc');
    // $list = $db->fetchAll('select * from news', 'num');
    // $list = $db->fetchAll('select * from news', 'both');
    $list = $db->fetchAll('select * from news', 'aa');
    echo '<pre>';
    var_dump($list);
?>

效果:
在这里插入图片描述
查询封装(一般三种,二维数组,一维数组,一行一列):

<?php
    class MySQLDB {
        private $host; // 主机地址
        private $port; // 端口号
        private $user; // 用户名
        private $pwd; // 密码
        private $dbname; // 数据库名
        private $charset; // 字符集 
        private $link; // 连接对象
        private static $instance;
        private function __construct($param) {
            $this->initParam($param);
            $this->initConnect();
        }
        private function __clone() {

        }
        public static function getInstance($param=array()) {
            if (!self::$instance instanceof self) {
                self::$instance = new self($param);
            }
            return self::$instance;
        }
        // 初始化成员
        private function initParam($param) {
            $this->host = $param['host']??'127.0.0.1';
            $this->port = $param['port']??'3306';
            $this->user = $param['user']??'';
            $this->pwd = $param['pwd']??'';
            $this->dbname = $param['dbname']??'';
            $this->charset = $param['charset']??'uft8';
        }
        // 连接数据库
        private function initConnect() {
            $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
            if (mysqli_connect_error()) {
                echo '数据库连接失败<br/>';
                echo '错误信息:'.mysqli_connect_error().'<br/>';
                exit;
            }
            mysqli_set_charset($this->link, $this->charset);
        }
        // 执行数据库的增、删、改、查
        private function execute($sql) {
           if (!$rs=mysqli_query($this->link, $sql)) {
               echo 'SQL语句执行失败<br/>';
               echo '错误信息:'.mysqli_error($this->link),'<br/>';
               echo '错误码:'.mysqli_error($this->link),'<br/>';
               echo '错误的SQL语句:'.$sql,'<br/>';
               exit;
           }
           else {
                return $rs;
           }
        }
        /**
         * 执行增、删、改
         * @return bool 成功返回true,失败返回false
         */
        public function exec($sql) {
            $key=substr($sql, 0, 6);
            if (in_array($key, array('insert', 'update', 'delete'))) {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            }
        }
        // 获取自动增长的编号
        public function getLastInsertId () {
            return mysqli_insert_id($this->link);
        }
        // 查询语句
        private function query($sql) {
            if (substr($sql, 0, 6) == 'select' || substr($sql, 0, 4) == 'show' || substr($sql, 0, 4) == 'desc') {
                return $this->execute($sql);
            }
            else {
                echo '非法访问';
                exit;
            } 
        }
        /**
         * 执行查询语句,返回二维数组
         * @$sql string 查询sql语句
         * @$type string assoc|num|both
         */
        public function fetchAll($sql, $type='assoc') {
            $rs = $this->query($sql);
            $type=$this->getType($type);
            return mysqli_fetch_all($rs, $type);
        }
        // 匹配一维数组
        public function fetchRow($sql, $type='assoc') {
            $list = $this->fetchAll($sql, $type);
            if (!empty($list)) {
                return $list[0];
            }
            return array();
        }
        // 匹配一行一列
        public function fetchColumn($sql) {
            $list = $this->fetchRow($sql, 'num');
            if (!empty($list)) {
                return $list[0];
            }
            else {
                return null;
            }
        }

        // 获取匹配类型
        private function getType($type) {
            switch($type) {
                // case 'assoc':
                //     return MYSQLI_ASSOC;
                case 'num':
                    return MYSQLI_NUM;
                case 'both':
                    return MYSQLI_BOTH;
                default:
                    return MYSQLI_ASSOC;
            } 
        }
    }
    // 假设配置文件
    $param=array(
        'dbname' => 'data',
        'user' => 'root',
        'pwd' => '123456'
    );


    // 测试 获取单例
    $db = MySQLDB::getInstance($param);
    // 查询
    // $list = $db->fetchAll('select * from news', 'assoc');
    // $list = $db->fetchAll('select * from news', 'num');
    // $list = $db->fetchAll('select * from news', 'both');
    // $list = $db->fetchAll('select * from news', 'aa');
    // $list = $db->fetchRow('select * from news where id=1', 'aa');
    $list = $db->fetchColumn('select count(*) from news');

    echo '<pre>';
    var_dump($list);
?>

效果:
在这里插入图片描述

在学习的php的路上,如果你觉得本文对你有所帮助的话,那就请关注点赞评论三连吧,谢谢,你的肯定是我写博的另一个支持。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你华还是你华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值