数据对象映射模式(及对象的相关属性和数据库表中的字段一一对应)

<?php
define("BASDIR",__DIR__);
include BASDIR."/Phpclass/Loader.php";
spl_autoload_register("\\Phpclass\\Loader::autoload_rege");

$user = new \Phpclass\User(1);

var_dump($user->id,$user->username,$user->phone_no,$user->retime);

$user->username = "nfyx1";//这里相当于 给user类中的属性赋值
$user->phone_no = "132451111111";
$user->retime = date("Y-m-d H-i-s");

//最后,在程序执行完时,调用__destruct()函数,把函数里的代码调协成update sql 语句,这时改变当前值,就等于更新一条数据。
-----------------------------------------------------------------------------------Index4.php
<?php
//对应的映射到数据库中的user
namespace Phpclass;


class User
{
public $id;
public $username;
public $phone_no;
public $retime;

protected $db;

function __construct($id)
{
$this->db= new Databases\Mysqlis();//创建一个Mysqlis对象,并把他保存到$db中;这里依赖于Databases目录下的Mysqlis.php文件
$this->db->connect("127.0.0.1","root","root","nfyx");//连接
$res=$this->db->query("select * from user where id=$id");//查询

$data=$res->fetch_assoc();//把结果集遍历成一个数组$data;

$this->id=$data['id'];//把数组中的值 赋值 给当前对应的变量;
$this->username=$data['username'];
$this->phone_no=$data['phone_no'];
$this->retime=$data['retime'];


}
function __destruct()
{
$this->db->query("update user set username='{$this->username}',phone_no='{$this->phone_no}',retime='{$this->retime}' where id='{$this->id}'");
}

}

-----------------------------------------------------------------------------------User.php,对应的数据库里的表
 
posted @ 2019-04-21 23:02  牛粪也香  阅读(2600)  评论(0编辑  收藏  举报