1.面向对象三大特征:封装、继承、多态
2.把某些重要属性封装起来,然后通过一个开放的接口来操作----封装
对于一个对象,对外界开放一个接口,调用接口时,内部进行的操作,不需要让外界知道,
隐藏了内部的一些实现细节
(对方法的封装)
3.权限限制问题
权限修饰符:用来说明属性/方法的权限特点-->只能写在属性/方法前
private 私有的,保护最严
protected保护的
public 公共的
如何区分:看发生在类的{}内还是类外
如何判断属性/方法 有没有权限访问:看访问时的位置
public的属性,在任意位置都可以访问
private只能在类定义的大括号内{}才能访问
例如:
class Human{
public $mood=' ';
private $money =1000;
public function showmoney(){
return $this->money;
}
private function secret(){
echo 'fgds<br/>';
}
public function tellme(){
$this->secret();
}
}
$lisi=new Human();
$lisi->mood='happy';
echo $lisi->mood;
echo '<br/>';
echo $lisi->showmoney();
echo '<br/>';
$lisi->tellme();
运行结果:happy
1000
fgds
4.Mysql类的封装(具体事例)
连接数据库
发送查询
对于select型返回查询数据
关闭MySQL连接
(这个代码是经过多次修改的,所以我想保存下来,感觉应该会挺有用哒)
class Mysql{
private $host;
private $user;
private $pwd;
private $dbName;
private $charset;
private $conn=null;//保存连接的资源
public function __construct(){
//构造方法里面读取配置文件
//然后根据配置文件设置私有属性
$this->host='localhost';
$this->user='root';
$this->pwd='';
$this->dbName='test';//没有配置所以直接赋值
$this->connect($this->host,$this->user,$this->pwd);//连接
$this->switchdb($this->dbName);//切换库
$this->setChar($this->charset);//设置字符集
}
private function connect($h,$u,$p){
$conn=mysqli_connect($h,$u,$p);
$this->conn=$conn;
}
public function switchdb($db){
$sql='use ' . $db;
$this->query($sql);
} //负责切换数据库
public function setChar($char){
$sql='set names '.$char;
$this->query($sql);
}//设置字符集
public function query($sql){
return mysqli_query($this->conn,$sql);
}
public function getAll($sql){
$list=array();
$rs=$this->query($sql);
if(!$rs){
return false;
}
while($row=mysqli_fetch_assoc($rs)){
$list[]=$row;
}
return $list;
//获取多行select结果
}
public function getRow($sql){
$list=array();
$rs=$this->query($sql);
if(!$rs){
return false;
}
return mysqli_fetch_assoc($rs);;
//获取一行select结果
}
public function getOne($sql){
$list=array();
$rs=$this->query($sql);
if(!$rs){
return false;
}
$row=mysqli_fetch_row($rs);
return $row[0];
//获取一条select语句结果
}
public function close(){
mysql_close($this->conn);
}
}
$mysql=new Mysql();
$sql="insert into stu values (20,'object','9998')";
var_dump($sql);
if($mysql->query($sql)){
echo 'query成功';
}else{
echo 'query失败';
}
echo '<br/>';
$sql='select * from stu';
$arr=$mysql->getAll($sql);
var_dump($arr);
$sql='select * from stu where id=1';
var_dump($mysql->getRow($sql));
$sql='select count(*) from stu';
var_dump($mysql->getOne($sql));
#注意:参数如何传呢?
1、用配置文件(一般的建议是用这个)
2、构造函数传参
#在封装Mysql类时一定要注意this的使用