至尊技术网 - 面向对象 https://www.zzwws.cn/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/ zh-CN Thu, 21 Jul 2022 11:20:03 +0800 Thu, 21 Jul 2022 11:20:03 +0800 PHP面向对象的链式调用方式 https://www.zzwws.cn/archives/6350/ https://www.zzwws.cn/archives/6350/ Thu, 21 Jul 2022 11:20:03 +0800 悠悠楠杉 实现起来也还蛮简单的,只需要在每个方法最后返回$this就可以了

<?php
class wc
{
    public function __construct($who)
    {
        echo "{$who}准备去上厕所了";
    }

    public function go()
    {
        echo "1.跑出了教室";
        return $this;
    }

    public function action($ss)
    {
        echo $ss . "2.到了厕所,开始尿尿";
        return $this;
    }

    public function back()
    {
        echo "3.尿尿结束,回到教室";
        return $this;
    }
}

$xm = new wc("小明");
$xm->go()->action("<br>")->back();

]]>
0 https://www.zzwws.cn/archives/6350/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象封装MySQL PDO(已使用预处理) https://www.zzwws.cn/archives/6343/ https://www.zzwws.cn/archives/6343/ Fri, 10 Jun 2022 11:38:00 +0800 悠悠楠杉 Mysql.class.php

<?php
class Mysql
{
    public $link;

    public function __construct()
    {
        $this->conn();
    }

    /**
     * 连接数据库,从配置文件读取配置信息
     */
    public function conn()
    {
        $cfg = require 'config.php';
        try {
            $this->link = new PDO("mysql:dbname={$cfg['databaseName']};host={$cfg['host']};charset={$cfg['charset']};port={$cfg['port']}", $cfg['name'], $cfg['password']);
            $this->link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // 设置禁止本地模拟prepare
            //$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// 设置捕获异常
        } catch (PDOException $e) {
            die("Error: " . $e->getMessage());
        }
    }

    /**
     * 查询多行数据
     * @param string $table 表名字
     * @param string $where where条件
     * @param string $field 字段
     * @param string $additional 附加sql语句
     * @return array
     */
    public function getAll($table, $where = [], $field = "*", $additional = '')
    {
        if (strpos($field, ",") !== false) {
            $arr = explode(",", $field);
            $str = '';
            foreach ($arr as $v) {
                $str .= "`{$v}`,";
            }
            $field = substr($str, 0, -1);
        } else if ($field != "*") {
            $field = "`{$field}`";
        }
        $sql = "SELECT {$field} FROM `{$table}`";
        $sql2 = '';
        $value = [];
        if ($where) {
            if (!is_array($where[0])) {
                if (strtolower($where[1]) == 'in') {
                    $where[1] = 'IN';
                    $sql2 = " `{$where[0]}` {$where[1]} (";
                    if (is_array($where[2])) {
                        foreach ($where[2] as $v) {
                            $value[] = $v;
                            $sql2 .= '?,';
                        }
                    } else {
                        $value[] = $where[2];
                        $sql2 .= '?';
                    }
                    $sql2 = rtrim($sql2, ',') . ')';
                } else {
                    $value[] = $where[2];
                    $sql2 = " `{$where[0]}` {$where[1]} ?";
                }
            } else {
                foreach ($where as $v) {
                    if (strtolower($v[1]) == 'in') {
                        $v[1] = 'IN';
                        $sql2 .= " `{$v[0]}` {$v[1]} (";
                        if (is_array($v[2])) {
                            foreach ($v[2] as $v2) {
                                $value[] = $v2;
                                $sql2 .= "?,";
                            }
                        } else {
                            $value[] = $v[2];
                            $sql2 .= "?";
                        }
                        $sql2 = rtrim($sql2, ',') . ') AND';
                    } else {
                        $value[] = $v[2];
                        $sql2 .= " `{$v[0]}` {$v[1]} ? AND";
                    }
                }
                $sql2 = substr($sql2, 0, -4);
            }
            if ($sql2) {
                $sql .= " WHERE " . $sql2;
            }
        }
        if ($additional) {
            $sql .= ' ' . $additional;
        }
        $res = $this->link->prepare($sql);
        $res->execute($value);
        $data = $res->fetchAll(PDO::FETCH_ASSOC);
        return $data;
    }

    /**
     * 查询单行数据
     * @param string $table 表名字
     * @param string $where where条件
     * @param string $field 字段
     * @param string $additional 附加sql语句
     * @return array
     */
    public function getRow($table, $where = [], $field = "*", $additional = '')
    {
        if (strpos($field, ",") !== false) {
            $arr = explode(",", $field);
            $str = '';
            foreach ($arr as $v) {
                $str .= "`{$v}`,";
            }
            $field = substr($str, 0, -1);
        } else if ($field != "*") {
            $field = "`{$field}`";
        }
        $sql = "SELECT {$field} FROM `{$table}`";
        $sql2 = '';
        $value = [];
        if ($where) {
            if (!is_array($where[0])) {
                if (strtolower($where[1]) == 'in') {
                    $where[1] = 'IN';
                    $sql2 = " `{$where[0]}` {$where[1]} (";
                    if (is_array($where[2])) {
                        foreach ($where[2] as $v) {
                            $value[] = $v;
                            $sql2 .= '?,';
                        }
                    } else {
                        $value[] = $where[2];
                        $sql2 .= '?';
                    }
                    $sql2 = rtrim($sql2, ',') . ')';
                } else {
                    $value[] = $where[2];
                    $sql2 = " `{$where[0]}` {$where[1]} ?";
                }
            } else {
                foreach ($where as $v) {
                    if (strtolower($v[1]) == 'in') {
                        $v[1] = 'IN';
                        $sql2 .= " `{$v[0]}` {$v[1]} (";
                        if (is_array($v[2])) {
                            foreach ($v[2] as $v2) {
                                $value[] = $v2;
                                $sql2 .= "?,";
                            }
                        } else {
                            $value[] = $v[2];
                            $sql2 .= "?";
                        }
                        $sql2 = rtrim($sql2, ',') . ') AND';
                    } else {
                        $value[] = $v[2];
                        $sql2 .= " `{$v[0]}` {$v[1]} ? AND";
                    }
                }
                $sql2 = substr($sql2, 0, -4);
            }
            if ($sql2) {
                $sql .= " WHERE " . $sql2;
            }
        }
        if ($additional) {
            $sql .= ' ' . $additional;
        }
        $res = $this->link->prepare($sql);
        $res->execute($value);
        $data = $res->fetch(PDO::FETCH_ASSOC);
        return $data;
    }

    /**
     * 自动创建sql语句并执行
     * @param string $table 表名字
     * @param array $data 关联数组 键/值与表的列/值对应
     * @param string $act 1为insert,2为update
     * @param array $where 条件,用于update
     * @return int 成功为insert产生的主键值,update是影响的行数,失败为0
     */
    public function exec($table, $data, $act = 1, $where = [])
    {
        $value = [];
        if ($act == 1) {
            $sql = "INSERT INTO `{$table}` (`";
            $sql .= implode('`,`', array_keys($data)) . '`)';
            $str = '';
            foreach ($data as $v) {
                $str .= "?,";
            }
            $str = substr($str, 0, -1);
            $sql .= " VALUES ({$str})";
            $value = array_values($data);
        } else {
            $sql = "UPDATE `{$table}` SET ";
            foreach ($data as $k => $v) {
                $sql .= "`" . $k . '`= ' . " ?,";
                $value[] = $v;
            }
            $sql = rtrim($sql, ',');
            $sql2 = '';
            if ($where) {
                if (!is_array($where[0])) {
                    if (strtolower($where[1]) == 'in') {
                        $where[1] = 'IN';
                        $sql2 = " `{$where[0]}` {$where[1]} (";
                        if (is_array($where[2])) {
                            foreach ($where[2] as $v) {
                                $value[] = $v;
                                $sql2 .= '?,';
                            }
                        } else {
                            $value[] = $where[2];
                            $sql2 .= '?';
                        }
                        $sql2 = rtrim($sql2, ',') . ')';
                    } else {
                        $value[] = $where[2];
                        $sql2 = " `{$where[0]}` {$where[1]} ?";
                    }
                } else {
                    foreach ($where as $v) {
                        if (strtolower($v[1]) == 'in') {
                            $v[1] = 'IN';
                            $sql2 .= " `{$v[0]}` {$v[1]} (";
                            if (is_array($v[2])) {
                                foreach ($v[2] as $v2) {
                                    $value[] = $v2;
                                    $sql2 .= "?,";
                                }
                            } else {
                                $value[] = $v[2];
                                $sql2 .= "?";
                            }
                            $sql2 = rtrim($sql2, ',') . ') AND';
                        } else {
                            $value[] = $v[2];
                            $sql2 .= " `{$v[0]}` {$v[1]} ? AND";
                        }
                    }
                    $sql2 = substr($sql2, 0, -4);
                }
                if ($sql2) {
                    $sql .= " WHERE " . $sql2;
                }
            }
        }
        $res = $this->link->prepare($sql);
        $run = $res->execute($value);
        if ($run) {
            if ($act == 1) {
                return $this->link->lastInsertId();
            } else {
                return $res->rowCount();
            }
        } else {
            return 0;
        }
    }

    /**
     * 删除数据
     * @param string $table 表名字
     * @param array $where where条件
     * @return bool
     */
    public function delete($table, $where = [])
    {
        $sql = "DELETE FROM `{$table}`";
        $sql2 = '';
        $value = [];
        if ($where) {
            if (!is_array($where[0])) {
                if (strtolower($where[1]) == 'in') {
                    $where[1] = 'IN';
                    $sql2 = " `{$where[0]}` {$where[1]} (";
                    if (is_array($where[2])) {
                        foreach ($where[2] as $v) {
                            $value[] = $v;
                            $sql2 .= '?,';
                        }
                    } else {
                        $value[] = $where[2];
                        $sql2 .= '?';
                    }
                    $sql2 = rtrim($sql2, ',') . ')';
                } else {
                    $value[] = $where[2];
                    $sql2 = " `{$where[0]}` {$where[1]} ?";
                }
            } else {
                foreach ($where as $v) {
                    if (strtolower($v[1]) == 'in') {
                        $v[1] = 'IN';
                        $sql2 .= " `{$v[0]}` {$v[1]} (";
                        if (is_array($v[2])) {
                            foreach ($v[2] as $v2) {
                                $value[] = $v2;
                                $sql2 .= "?,";
                            }
                        } else {
                            $value[] = $v[2];
                            $sql2 .= "?";
                        }
                        $sql2 = rtrim($sql2, ',') . ') AND';
                    } else {
                        $value[] = $v[2];
                        $sql2 .= " `{$v[0]}` {$v[1]} ? AND";
                    }
                }
                $sql2 = substr($sql2, 0, -4);
            }
            if ($sql2) {
                $sql .= " WHERE " . $sql2;
            }
        }
        $res = $this->link->prepare($sql);
        return $res->execute($value);
    }

    /**
     * count数据
     * @param string $table 表名字
     * @param array $where where条件
     * @param string $field 字段
     * @return int
     */
    public function count($table, $where = [],$field = '*')
    {
        $sql = "SELECT COUNT({$field}) FROM `{$table}`";
        $sql2 = '';
        $value = [];
        if ($where) {
            if (!is_array($where[0])) {
                if (strtolower($where[1]) == 'in') {
                    $where[1] = 'IN';
                    $sql2 = " `{$where[0]}` {$where[1]} (";
                    if (is_array($where[2])) {
                        foreach ($where[2] as $v) {
                            $value[] = $v;
                            $sql2 .= '?,';
                        }
                    } else {
                        $value[] = $where[2];
                        $sql2 .= '?';
                    }
                    $sql2 = rtrim($sql2, ',') . ')';
                } else {
                    $value[] = $where[2];
                    $sql2 = " `{$where[0]}` {$where[1]} ?";
                }
            } else {
                foreach ($where as $v) {
                    if (strtolower($v[1]) == 'in') {
                        $v[1] = 'IN';
                        $sql2 .= " `{$v[0]}` {$v[1]} (";
                        if (is_array($v[2])) {
                            foreach ($v[2] as $v2) {
                                $value[] = $v2;
                                $sql2 .= "?,";
                            }
                        } else {
                            $value[] = $v[2];
                            $sql2 .= "?";
                        }
                        $sql2 = rtrim($sql2, ',') . ') AND';
                    } else {
                        $value[] = $v[2];
                        $sql2 .= " `{$v[0]}` {$v[1]} ? AND";
                    }
                }
                $sql2 = substr($sql2, 0, -4);
            }
            if ($sql2) {
                $sql .= " WHERE " . $sql2;
            }
        }
        $res = $this->link->prepare($sql);
        $res->execute($value);
        $data = $res->fetch(PDO::FETCH_NUM);
        return $data[0];
    }
}

config.php

<?php
return array(
    'host' => 'localhost',
    'name' => 'root',
    'password' => 'root',
    'databaseName' => 'cs_cn',
    'port' => '3306',
    'charset' => 'utf8'
);

使用方法

<?php
require 'Mysql.class.php';

$mysql = new Mysql();

// 添加
$data = [
    'code' => mt_rand(1000000000,9999999999),
    'url' => 'https://www.zzwws.cn',
    'ip' => mt_rand(1000000000,9999999999),
    'add_time' => time()
];
$res = $mysql->exec('zz_url',$data);
if($res){
    echo '添加成功';
}else{
    echo '添加失败';
}

// 修改
$data = [
    'code' => mt_rand(1000000000,9999999999)
];
$where = ['id','=',51];
// 或者
// $where = [
//     ['id','=',51],
//     ['ip','=','3755406202']
// ];

$res = $mysql->exec('zz_url',$data,2,$where);
if($res){
    echo '修改成功';
}else{
    echo '修改失败';
}

// 查询一行数据
$row = $mysql->getRow('zz_url',['id','=',51],'id,code');
if(!$row){
    echo '获取失败';
}
print_r($row);

// 查询多行数据
$rows = $mysql->getAll('zz_url');
print_r($rows);

// 删除
$where = [
    ['id','=',52]
];
// 或者
// $where = [
//     ['id','in',[1,2,3]]
// ];
$res = $mysql->delete('zz_url',$where);
var_dump($res);

// count
$count = $mysql->count('zz_url',['url','=','https://www.zzwws.cn']);
var_dump($count);

// query方法(没有预处理)
$res = $mysql->link->query("SELECT * FROM zz_url WHERE id = '1'");
$row = $res->fetch(PDO::FETCH_ASSOC);
print_r($row);
]]>
0 https://www.zzwws.cn/archives/6343/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象封装Redis、Memcached、Memcache实例 https://www.zzwws.cn/archives/5020/ https://www.zzwws.cn/archives/5020/ Tue, 12 Jan 2021 11:40:00 +0800 悠悠楠杉 Cache.class.php

<?php
class Mysql
{
    public $link;

    public function __construct()
    {
        $this->conn();
    }
    /**
     * 连接数据库,从配置文件读取配置信息
     */
    public function conn()
    {
        $cfg = require 'config.php';
        $this->link = new mysqli($cfg['host'], $cfg['name'], $cfg['password'], $cfg['databaseName'], $cfg['port']);
        $this->query('set names ' . $cfg['charset']);
    }
    /**
     * 发送query查询
     * @param string $sql sql语句
     * @return mixed
     */
    public function query($sql)
    {
        return $this->link->query($sql);
    }

    /**
     * 查询多行数据
     * @param string $sql sql语句
     * @return array
     */
    public function getAll($sql)
    {
        $res = $this->query($sql);
        $data = [];
        while ($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    }
}

class Cache
{
    public $m;
    public function __construct()
    {
        //创建实例
        
        //Redis 使用前需要重启PHP和Redis
        $this->m = new Redis();
        $this->m->connect('127.0.0.1', 6379);
        $this->m->auth('password');//Redis密码,设置、修改密码后需要重载配置

        //Memcached
        /*$this->m = new Memcached();
        $this->m->addServer('127.0.0.1', 11211);*/

        //Memcache
        /*$this->m = new Memcache();
        $this->m->connect('127.0.0.1', 11211);*/
    }
    /**
     * 添加
     * @param string $key 用于存储值的键名
     * @param string $value 存储的值
     * @return boolean
     */
    public function memAdd($key, $value)
    {
        return $this->m->set($key, $value);
    }

    /**
     * 获取
     * @param string $key 要检索的元素的key
     * @return string 失败返回false
     */
    public function memGet($key)
    {
        return $this->m->get($key);
    }

    /**
     * 删除
     * @param string $key 要删除的元素的key
     * @return bool 失败返回false
     */
    public function del($key)
    {
        return $this->m->delete($key);
    }

    /**
     * 清空
     * @return bool 失败返回false
     */
    public function clear()
    {
        return $this->m->flushDB();
    }

    /**
     * 获取使用序列化来存储数据
     * @param string $key 可以是md5加密后的sql语句
     * @param string $sql sql语句
     * @return array
     */
    public function selectMsg($key, $sql)
    {

        //先查询数据缓存是否有该数据
        $msg = $this->memGet($key);
        //没有则查询数据库
        // var_dump($msg);
        if (!$msg) {
            echo '跑数据库';
            $mysql = new Mysql();
            $list = $mysql->getAll($sql);
            //var_dump($list);
            //把查询出来的结果序列化存进memcached中
            $data = serialize($list);
            $this->memAdd($key, $data);
            //返回数据库查找的值
            return $list;
        } else {
            echo '不跑数据库';
            //有则反序列输出
            return unserialize($msg);
        }
    }
}

//调用
$cache = new Cache();
$sql = 'select * from art';
$key = md5($sql);
$list = $cache->selectMsg($key,$sql);
var_dump($list);

//更新数据
$cache->memAdd($key,null);

//删除数据
$cache->del($key);

//清空数据
$cache->clear();

config.php

<?php
return array(
    'host' => 'localhost',
    'name' => 'cs',
    'password' => '123456',
    'databaseName' => 'cs',
    'port' => '3306',
    'charset' => 'utf8'
);
]]>
0 https://www.zzwws.cn/archives/5020/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP Smarty 模板引擎 https://www.zzwws.cn/archives/4999/ https://www.zzwws.cn/archives/4999/ Wed, 06 Jan 2021 15:03:00 +0800 悠悠楠杉 1.php

<?php
class Mini
{
    protected $data = array();
    //把外界变量放进data数组
    public function assign($k, $v)
    {
        $this->data[$k] = $v;
    }
    public function comp($temp)
    {
        $html = file_get_contents($temp);
        //注意 下行引用自身的data属性
        $html = str_replace('{$', "<?php echo \$this->data['", $html);
        $html = str_replace('}', "'];?>", $html);
        $compfile = $temp . '.php';
        file_put_contents($compfile, $html);
        return $compfile;
    }
    public function display($temp)
    {
        $compfile = $this->comp($temp);
        require $compfile;
    }
}
$sql = "select * from art";
$title = '今天不下雨,ε=(´ο`*)))';
$mini = new Mini();
$mini->assign('title', $title);
$mini->display('1.html');

1.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
    <p>{$title}</p>
</body>

</html>
]]>
0 https://www.zzwws.cn/archives/4999/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象封装MySQL操作函数、文件上传 https://www.zzwws.cn/archives/4997/ https://www.zzwws.cn/archives/4997/ Mon, 04 Jan 2021 17:36:00 +0800 悠悠楠杉 Mysql.class.php

<?php
class Mysql
{
    public $link;

    public function __construct()
    {
        $this->conn();
    }

    /**
     * 连接数据库,从配置文件读取配置信息
     */
    public function conn()
    {
        $cfg = require 'config.php';
        $this->link = new mysqli($cfg['host'], $cfg['name'], $cfg['password'], $cfg['databaseName'], $cfg['port']);
        $this->query('set names ' . $cfg['charset']);
    }

    /**
     * 发送query查询
     * @param string $sql sql语句
     * @return mixed
     */
    public function query($sql)
    {
        return $this->link->query($sql);
    }

    /**
     * 查询多行数据
     * @param string $sql sql语句
     * @return array
     */
    public function getAll($sql)
    {
        $res = $this->query($sql);
        $data = [];
        while ($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    }

    /**
     * 查询单行数据
     * @param string $sql sql语句
     * @return array
     */
    public function getRow($sql)
    {
        $res = $this->query($sql);
        return $res->fetch_assoc();
    }

    /**
     * 查询单个数据
     * @param string $sql sql语句
     * @return array mixed
     */
    public function getOne($sql)
    {
        $res = $this->query($sql);
        return $res->fetch_row()[0];
    }

    /**
     * 自动创建sql语句并执行
     * @param string $table 表名字
     * @param array $data 关联数组 键/值与表的列/值对应
     * @param string $act 动作/update/insert
     * @param string $where 条件,用于update
     *
     */
    public function exec($table, $data, $act = 'insert', $where = '0')
    {

        if ($act == 'insert') {
            //插入语句 insert into 表名 (字段1,字段2) values ('values1','values2')
            $sql = "insert into $table (";
            $sql .= implode(',', array_keys($data)) . ')';
            $sql .= " values ('";
            $sql .= implode("','", array_values($data)) . "')";
        } else {
            //修改语句 update 表名 set 字段1='values1',字段2='values2' where id=1
            $sql = "update $table set ";
            foreach ($data as $k => $v) {
                $sql .= $k . '=' . "'$v',";
            }
            $sql = rtrim($sql, ',');
            $sql .= " where $where";
        }
        return $this->query($sql);
    }

    /**
     * 返回上一条insert语句产生的主键值
     */
    public function lastId()
    {
        return $this->link->insert_id;
    }

    /**
     * 返回上一条语句影响的行数
     */
    public function affectRows()
    {
        return $this->link->affected_rows;
    }
}

Upload.class.php

<?php
abstract class AUpload
{
    public $allowext = array('jpg', 'jpeg', 'png', 'rar');
    public $maxsize = 1;
    protected $error = '';

    abstract public function getInfo($name);
    abstract public function createDir();
    abstract public function randStr($len = 8);
    abstract protected function checkType($ext);
    abstract protected function checkSize($size);
    abstract public function up($name);

    public function getError()
    {
        return $this->error;
    }
}

class Upload extends AUpload
{
    /**
     * 分析$_FILES中$name域的信息,比如$_FILES['pic']
     * @param string $name 表单中的file里的name值
     * @return array 上传文件的信息
     */
    public function getInfo($name)
    {
        return $_FILES[$name];
    }

    /**
     * 创建目录 /upload/2021/01/04
     * @return string 目录路径
     */
    public function createDir()
    {
        $dir = '/upload/' . date('Y/m/d');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        return $dir;
    }

    /**
     * 生成随机字符串
     * @param int $len 随机字符串的长度
     * @return string 返回生成的字符串
     */
    public function randStr($len = 6)
    {
        $str = str_shuffle('abcedfghjkmnpqrstuvwxyzABCEDFGHJKMNPQRSTUVWXYZ0123456789');
        return substr($str, 0, $len);
    }

    /**
     * 检查文件类型
     * @param $ext 文件后缀
     * @return boolean
     */
    protected function checkType($ext)
    {
        return in_array($ext, $this->allowext);
    }

    /**
     * 检测文件大小
     * @param $size 文件大小
     * @return boolean
     */
    protected function checkSize($size)
    {
        return $size < $this->maxsize * 1024 * 1024;
    }

    /**
     * 上传文件
     * @param string $name 表单中file的name值
     * @return string 上传的文件,如/upload/2021/01/04/1609749834kfyzXr.jpg
     */
    public function up($name)
    {
        if (!isset($_FILES[$name])) {
            echo '没有上传文件';exit();
        }
        $info = $this->getInfo($name);

        $ext = ltrim(strrchr($info['name'], '.'), '.');
        if (!$this->checkType($ext)) {
            echo '不允许上传此类型文件';exit();
        }

        if (!$this->checkSize($info['size'])) {
            echo '文件过大';exit();
        }

        $dir = $this->createDir();
        $filename = time() . $this->randStr() . '.' . $ext;
        if (move_uploaded_file($info['tmp_name'], $dir . '/' . $filename)) {
            $data['path'] = $dir;
            $data['filename'] = $filename;
            return $data;
        } else {
            echo '上传失败';
        }
    }
}

$file = new Upload();
var_dump($file->up('pic'));

upload.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>上传</title>
</head>

<body>
    <form action="Upload.class.php" method="post" enctype="multipart/form-data">
        <input type="file" name="pic">
        <button type="submit" id="submit">提交</button>
    </form>

</body>

</html>

config.php

<?php
return array(
    'host' => 'localhost',
    'name' => 'cs',
    'password' => '123456',
    'databaseName' => 'cs',
    'port' => '3306',
    'charset' => 'utf8'
);

使用方法

$mysql = new Mysql();

1、增

$art['title'] = trim($_POST['title']);
$art['cat_id'] = trim($_POST['cat_id']);
$art['content'] = trim($_POST['content']);
$art['pubtime'] = time();
if ($mysql->exec('art', $art)) {
        echo('添加成功');
    } else {
        echo('添加失败');
    }

2、删

$sql = "delete from cat where cat_id='$cat_id'";
if ($mysql->query($sql)) {
    echo('删除成功');
} else {
    echo('删除失败');
}

3、改

$cat_id = $_GET['cat_id'];
$cat['catname'] = trim($_POST['catname']);
if ($mysql->exec('cat',$cat,'update',"cat_id=$cat_id")) {
    echo('修改成功');
} else {
    echo('修改失败');
}

4、查
查询多行数据

$sql = "select * from cat";
$arr = $mysql->getAll($sql);
print_r($arr);

取出一行数据

$sql = "select * from cat where cat_id='$cat_id'";
if (!$mysql->getRow($sql)) {
    echo('栏目不存在');
    exit();
}

查询返回一个结果

$sql = "select * from cat where cat_id='$cat_id'";
echo $mysql->getOne($sql);

获取上一步insert 操作产生的主键id

$mysql->lastId();


]]>
0 https://www.zzwws.cn/archives/4997/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象的自动加载 https://www.zzwws.cn/archives/4996/ https://www.zzwws.cn/archives/4996/ Wed, 30 Dec 2020 17:46:54 +0800 悠悠楠杉 实例化某个类时,如MySQL类,需要先require('mysql.php' );
如果类比较多,目录也比较多,require文件时,将会变得麻烦
我们需要一个自动化的解决方法--自动加载

用法:
声明一个函数,并注册为"自动加载函数"
当系统发现某个类不存在时,会调用此函数,我们可以在函数中加载需要的类文件

<?php
function myLoad($class){
    require $class . '.php';
}

//把myLoad注册成自动加载函数
spl_autoload_register('myLoad');

new mysql();//查看效果
]]>
0 https://www.zzwws.cn/archives/4996/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象中的魔术方法 https://www.zzwws.cn/archives/4995/ https://www.zzwws.cn/archives/4995/ Wed, 30 Dec 2020 17:04:00 +0800 悠悠楠杉 魔术方法:某种场景下,能够自动调用的方法
如: __construct、 __destruct、__set、 __get、 __isset、__unset、__call
__construct(): 构造方法,new 实例时,自动调用
__destruct(): 析构方法,对象销毁时自动调用
__get(属性名): 当读取对象的一个不可见属性时,自动调用,并返回值

不可见: 未定义或无权访问时
__set(属性名,属性值): 当对一个不可见的属性赋值时,自动调用
__isset(属性名): 当用isset,或empty判断一个不可见属性时,自动调用
__unset(属性名): 当unset一个不可见属性时,自动调用

<?php
class Human{
    //构造方法,new 实例时,自动调用
    public function __construct(){
        echo '构造方法';
    }

    //析构方法,对象销毁时自动调用
    public function __destruct(){
        echo '析构方法';
    }

    //当读取对象的一个不可见属性时,自动调用,并返回值
    public function __get($a){
        echo $a;
    }

    //当对一个不可见的属性赋值时,自动调用
    public function __set($b,$c){
        echo $b.'-'.$c;
    }

    //当用isset,或empty判断一个不可见属性时,自动调用
    public function __isset($d){
        echo $d;
    }

    //当unset一个不可见属性时,自动调用
    public function __unset($f){
        echo $f;
    }
}
$zhangSan = new Human();

$zhangSan->daQiu;//daQiu

$zhangSan->kan = '变形金刚';//kan-变形金刚

isset($zhangSan->zhangFei);//zhangFei

unset($zhangSan->liuBei);//liuBei
]]>
0 https://www.zzwws.cn/archives/4995/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/
PHP面向对象中的$this、self、parent https://www.zzwws.cn/archives/4990/ https://www.zzwws.cn/archives/4990/ Tue, 29 Dec 2020 11:18:22 +0800 悠悠楠杉 <?php // $this 本对象 // self 本类 // parent 父类 class Single { public $rand; public static $ob; //final 方法不能被子类重写,实现单例模式 final protected function __construct() { $this->rand = mt_rand(1000, 9999); } public static function getins() { if (self::$ob == null) { self::$ob = new self(); } return self::$ob; } } var_dump(Single::getins()); class Par { public function __construct() { echo mt_rand(10000, 99999); } } class Son extends Par { public function __construct() { parent::__construct(); echo 1; } } new Son(); ]]> 0 https://www.zzwws.cn/archives/4990/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/ PHP面向对象中单例模式 https://www.zzwws.cn/archives/4989/ https://www.zzwws.cn/archives/4989/ Tue, 29 Dec 2020 10:54:00 +0800 悠悠楠杉 <?php class Single { public $rand; public static $ob; //final 方法不能被子类重写,实现单例模式 final protected function __construct() { $this->rand = mt_rand(1000, 9999); } public static function getins() { if (Single::$ob == null) { Single::$ob = new Single(); } return Single::$ob; } } var_dump(Single::getins()); var_dump(Single::getins()); ]]> 0 https://www.zzwws.cn/archives/4989/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/ PHP中面向对象3种权限详解 https://www.zzwws.cn/archives/4988/ https://www.zzwws.cn/archives/4988/ Mon, 28 Dec 2020 17:38:00 +0800 悠悠楠杉 public(公有)protected(受保护)private(私有)外部YNN子类中YYN本类中YYY
<?php
class Human
{
    public $money = '3000';
    protected $car = 'BMW';
    private $gf = 'mv';
    public function par()
    {
        echo $this->money;
        echo $this->car;
        echo $this->gf;
    }
}
class Stu extends Human
{
    public function sub()
    {
        echo $this->money;
        echo $this->car;
        echo $this->gf;
    }
}
$stu = new Stu;
$stu->par();
$stu->sub(); //gf没有被继承
echo $stu->money;
echo $stu->car; //无权限访问
echo $stu->gf; //无权限访问

]]>
0 https://www.zzwws.cn/archives/4988/#comments https://www.zzwws.cn/feed/tag/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/