作业1-2:类声明与类的实力化、类常量和类属性的重载
实例
<?php //类的声明和实例化: class PC{ private $cpu; private $vcard; private $disk; private $price=1200; private $real_price=12; //常量 const BRAND = "hp"; //静态属性 static $sole = "供 货商1"; //构造函数,初始化赋值 public function __construct($cpu="",$vcard="",$disk="") { $this->cpu = $cpu; $this->vcard = $vcard; $this->disk = $disk; } //设置属性的重载 public function __set($name,$value){ if ($name =="price") { echo "价格不可以设置"; }else{ $this->$name = $value; } } //获取属性的重载 public function __get($name){ if(isset($this->$name)){ return $this->$name; }else{ echo "没有这个属性"; } // if (isset($this->$name)) { // return $this->$name; // }else{ // echo null; // } } //属性检测的重载 function __isset($name){ if($name =="real_price"){ echo "没有权限"; }else{ return isset($this->$name); } } //销毁属性的重载 public function __unset($name) { if ($name == 'real_price') { echo "没有权限"; return false; } unset($this->$name); } } //实例化一个类 $pc1 = new PC('i5','1050ti','120g'); echo "配置1的cpu是:",$pc1->cpu,"显卡是:",$pc1->vcard,"硬盘有",$pc1->disk; //实例化第二个类 $pc2 = new PC('i7','1060ti','256g'); echo "<br>配置2的cpu是:",$pc1->cpu,"显卡是:",$pc1->vcard,"硬盘有",$pc1->disk; //不允许更改的属性尝试 echo "<br>尝试改一下价格=>"; $pc2->price = 1233; echo "<br>尝试获取一下一个类没有的属性=>"; echo "<strong style='color:red'>",$pc2->box,"</strong>"; echo "<br>改一下配置2,增加一个内存条,显卡升级到1080ti<br>"; $pc2->bank = "8g"; $pc2->vcard ="1080ti"; echo "配置2的cpu是:",$pc2->cpu,"显卡是:",$pc2->vcard,"硬盘有",$pc2->disk,"增加了内存:",$pc2->bank; //获取常量属性-牌子 echo "<br>牌子:".PC::BRAND; //静态属性无法访问 echo $pc2->sole; //静态属性需要这样访问 echo "<br>供 货商是:".PC::$sole; //检测属性 isset($pc2->real_price); unset($pc2->real_price); ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例
3.静态函数和静态变量:
实例
<?php //静态成员和静态方法 class CONN{ //定义静态变量 public static $dsn=null; protected static $config = [ 'host' =>'localhost', 'type' =>'mysql', 'user' =>'abc', 'pwd' =>'abc', 'db_name' =>'test', ]; //静态连接函数 public static function connect(){ try{ $dsn = self::$db['type'].':host='.self::$db['host'].';dbname='.self::$db['dbname']; $pdo = new PDO($dsn,self::$db['user'],self::$db['pass']); }catch(PDOException $e){ echo $e->getMessage(); } } public static function select($table,$fields='*', $num=5) { $stmt = self::$pdo->prepare("SELECT {$fields} FROM {$table} LIMIT {$num}"); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } //连接数据库 Demo5::connect(); //查询数据表 $result = Demo5::select('staff','name,age,salary',8); //显示结果 echo '<pre>',var_export($result); ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例