Home >Backend Development >PHP Tutorial >这个代码可以改写成一个类吗?

这个代码可以改写成一个类吗?

WBOY
WBOYOriginal
2016-06-23 13:13:56982browse

比如这两段代码有很多重复的地方  我想把他们封装成一个类  每次用的时候就调用这个类   可是我没有写过类 什么构造函数 public private什么的都懂  就是不会写   感觉面向对象太抽象了 不知道从哪里开始写  谁能教教我怎么写这个类呢?

<?php$pdo=new PDO("mysql:host=localhost;dbname=t1","root","");		$id=$_GET["id"];		$stmt=$pdo->prepare("select * from user where username=?");		$stmt->execute(array($id));		$res=$stmt->fetchall();		if($res){			echo "用户名已被占用";		}else{		   echo "可以使用";		}?>

<?php$pdo=new PDO("mysql:host=localhost;dbname=t1","root","");$id=$_GET["id"];$stmt=$pdo->prepare("select * from user where email=?");$stmt->execute(array($id));$res=$stmt->fetchall();if($res){	echo "邮箱已被占用";}else{   echo "可以使用";}?>


回复讨论(解决方案)

没必要封装,不过可以写成这样。

<?phpfunction doit($id, $field, $name){		$pdo=new PDO("mysql:host=localhost;dbname=t1","root","");        $id=$_GET["id"];        $stmt=$pdo->prepare("select * from user where ".$field."=?");        $stmt->execute(array($id));        $res=$stmt->fetchall();        if($res){            echo '<span style="color: #FF0000;">'.$name.'</span>已被占用';        }else{           echo "可以使用";        }}doit($id, 'username', '用户名');doit($id, 'email', '邮箱');?>

封装成个函数就可以了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn