Blogger Information
Blog 61
fans 0
comment 0
visits 54318
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
构造方法的定义与实例
笑颜常开的博客
Original
920 people have browsed it

<?php
/**
* Created by PhpStorm.
* User: 廖广
* Date: 2019/3/25
* Time: 21:55
*/
//class demo04{
////    抽象对象属性
//    public $product;
//    public $price;
////    构造方法(构造器),本质也是一个对象方法
//    public function __construct($product,$price)
//    {
//        $this->product=$product;
//        $this->price=$price;
//    }
////    对象方法
//    public function getInfo(){
//        return '品名:'.$this->product.',价格:'.$this->price.'<br>';
//    }
//}
//$obj=new demo04('电脑',5000);
//echo $obj->getInfo();
//echo '<hr>';

//实战:自动连接数据库
class Db{
   //连接参数:PDO
   public $dsn;
   public $user;
   public $password;
   //连接对象
   public $pdo;
   //连接方法
   public function connect(){
       $this->pdo=new PDO($this->dsn,$this->user,$this->password);
   }
//    构造方法:希望在实例化的时候,自动连接数据库
   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 '<h3>连接成功</h3>';
}
//读取数据库测试
$stmt=$db->pdo->prepare('select * from staff');
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $staff){
       print_r($staff);echo '<br>';
}

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