实例(演示构造函数的功能)
<?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>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例