Home >Backend Development >PHP Tutorial >php面向对象怎样写实例呢?

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

WBOY
WBOYOriginal
2016-06-06 20:17:111528browse

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

回复内容:

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

还没更新完。。。

如果你为一张表写映射

1、刚开始你可以这么写

<code>class Table {
    public $id = NULL;
    public $title = NUll;
}</code>
<code>$table = new Table();
$table->id = 1000;
$table->title ='映射';

var_dump($table);</code>

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

于是这个是不是更方便?

<code>class Table {

    public function __set($property,$value){
        return $this->$property = $value;
    }
}</code>
<code>$table = new Table();
$table->id = 1000;
$table->title = 'PHP里__set()怎么用?';
$table->created_at = time();
var_dump($table);
</code>

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

<code>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;</code>

你可以在方法里任意发挥想象,只是尽量遵循参数和返回值的规范。有一个例子,就是将类的数组属性转换成一组独立属性

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