php面向对象怎样写实例呢?

查看:86
本文介绍了php面向对象怎样写实例呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

看了几天面向对象 也大概知道一点面向对象的知识了 可是就是不知道在实际运用中是怎么样实现的 怎样写一些简单的小例子呢 比如__get和__set在实际工作中是怎么用的呢

解决方案

还没更新完。。。

如果你为一张表写映射

1、刚开始你可以这么写

class Table {
    public $id = NULL;
    public $title = NUll;
}

$table = new Table();
$table->id = 1000;
$table->title ='映射';

var_dump($table);

2、数据表更变了,加了一个created_at,于是怎么办?改文件还是?

于是这个是不是更方便?

class Table {

    public function __set($property,$value){
        return $this->$property = $value;
    }
}

$table = new Table();
$table->id = 1000;
$table->title = 'PHP里__set()怎么用?';
$table->created_at = time();
var_dump($table);

3、从数据库中映射出来行(大概示意下)

class Table {
    
    public $tableName = NULL;
    
    public function loadFromMysqlRowResult($row){
        foreach($row as $property=>$value){
            $this->__set($property,$value);
        }
        return $this;
    }

    public function __set($property,$value){
        return $this->$property = $value;
    }
}

class News extends Table {
    
    private $db = NULL;
    
    public function __construct($db){
        $this->db = $db;
        $this->tableName = strtolower(__CLASS__);
    }
    
    public function findOne($id){
        $query = $this->db->query("select * from news where id=".$id)->fetch(PDO::FETCH_ASSOC);
        return self::loadFromMysqlRowResult($query);
    }
    
}

$db = new PDO('mysql:host=localhost;dbname=test','root','c313c313');
$newsModel = new News($db);
$news = $newsModel->findOne(1);
echo $news->title;

这篇关于php面向对象怎样写实例呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆