封装类(Merry May Day to all you who are burried in work ~)---2017-05-01
Posted 茶瓶儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装类(Merry May Day to all you who are burried in work ~)---2017-05-01相关的知识,希望对你有一定的参考价值。
1、为什么要使用封装类?
(1) 可以多个地方调用,避免代码的冗余
(2)面向对象三大特点之一,安全性高
2、代码及注意点?
<?php class DB //文件名为:DB.class.php 类名必须与文件名前面相同 { public $host = "localhost"; public $uid = "root"; public $pwd = "123"; public $dbname ="friends"; //$type 代表SQL语句的类型,0代表增删改 1代表查询 默认为查询,所以不传第二个参数时就是查询 function query($sql,$type = 1) { $db = new mysqli($this->host,$this->uid,$this->pwd,$this->dbname); $result = $db ->query($sql); if ($type) { //如果是查询,返回数据 return $result ->fetch_all(); } else{ //如果是增删改,返回true或false return $result; } } } ?>
注:
类名与方法类名的命名规则:
类名:驼峰命名法---单词首字母都有大写
方法类名:驼峰命名法,但是第一个单词首字母要小写
3、如何调用?
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <select> <?php require "DB.class.php"; //调用 $db = new DB(); $sql = "select name from friend"; $arr = $db->query($sql); //此处返回的二维数组,不再是结果集 foreach($arr as $v) { echo "<option >{$v[0]}</option>"; } ?> </select> </body> </html>
祝今天仍在劳动的人,五一节快乐~
merry May Day to you~
以上是关于封装类(Merry May Day to all you who are burried in work ~)---2017-05-01的主要内容,如果未能解决你的问题,请参考以下文章
idea not all local changes may be shown due to an error
idea使用svn提交时出现错误Warning not all local changes may be shown due to an error
解决Android Studio出现Failed to open zip file. Gradle's dependency cache may be corrupt的问题
We all live in the past. We take a minute to know someone, one hour to like someone, and one day t