Blogger Information
Blog 29
fans 0
comment 0
visits 25411
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2. 实例演示构造函数的功能
连界现代周伟的博客
Original
1197 people have browsed it

实例(演示构造函数的功能)

<?php
//数据库连接实例,演示构造函数
class Db
{
    //(属性)连接参数
    public $dsn;
    public $user;
    public $password;
    //对象pdo
    public $pdo;
    //对象方法:用于连接数据库
    public function connect()
    {
        $this->pdo = new PDO($this->dsn,$this->user,$this->password);
    }
    //构造函数,构造器  实例化Db
    public function __construct($dsn,$user,$password)
    {
        $this->dsn = $dsn;
        $this->user = $user;
        $this->password = $password;

        $this->connect();
    }
}

$db = new Db('mysql:host=127.0.0.1;dbname=php','root','root');
if ($db->pdo) {
    echo '数据库连接成功';
}
echo '<hr>';

$stmt = $db->pdo->prepare('SELECT * FROM `staff` LIMIT 10');
$stmt->execute();
$staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($staffs as $staff) {
    print_r($staff);echo '<br>';
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post