<?php
/*
?* WEB开发笔记 www.chhua.com 每日练习之PHP的静态方法与静态属性,只能通过类而不能通过类的实例来访问
?*/
class StaticExample {
?static public $name=chenhua;
?static public function write(){
??echo self::$name;//SELF关键字调用静态属性
?}
?
?public function writeName($website){
??echo $website;
?}
}

StaticExample::write();//静态方法
StaticExample::writeName(“www.chhua.com”);//非静态方法
/*一个很经典的把原始数据转换成对象的例子*/
//====================================================================
class Product {//基类
?private? $name;
?private $type;
?protected $jige;
?
?public function __construct($name,$type,$jage){
??$this->name=$name;
??$this->type=$type;
??$this->jige=$jage;
?}
?
?public function getName(){//访问方法
??return $this->name;
?}
?public function getType(){
??return $this->type;
?}
?public function getJiage(){
??return $this->jige;
?}
?
?public function get_zhaiyao(){
??$zhaiyao=$this->name.”({$this->type})<br>价格:{$this->jige}<br>”;
??return $zhaiyao;
?}
}

class BookProduct extends Product {//继承基类
?private $numpages;
?
??? public function __construct($name,$type,$jige,$numpages=0){
??parent::__construct($name,$type,$jige);//访问父类的方法
??$this->numpages=$numpages;
?}
?public function getPages(){//独有方法
??return $this->numpages;
?}
?
?public function get_zhaiyao(){//重载方法
??$zhaiyao=parent::get_zhaiyao();//调用父类的方法
??$zhaiyao.=”Page Count-{$this->numpages}页”;
??return $zhaiyao;
?}
}

class CdProduct extends Product{//继承基类
?private $playlength;
?
public function __construct($name,$type,$jiage,$playlength=0){
??parent::__construct($name,$type,$jiage);
??$this->playlength=$playlength;
?}
?public function getTimes (){//独有方法
??return $this->playlength;
?}
?
?public function get_zhaiyao(){//重载方法
??$zhaiyao=parent::get_zhaiyao();//调用父类的方法
??$zhaiyao.=”Play Length-{$this->playlength}分”;
??return $zhaiyao;
?}
}

//====================================================================

//把原始数据转换成对象

class getProduct {
?private $id=0;
?
?public function setId($id){
??$this->id=$id;
?}
?static function getInstance($id,PDO $pdo){
??$sql=”select * from products where id=’$id'”;
??$result=$pdo->query($sql);
??$row=$result->fetch();
??
??if (empty($row)) return null;
??
??if ($row[“type”]==”book”){
???$product=new BookProduct($row[“name”],
??????????????????????????? $row[“type”],
??????????????????????????? $row[“jiage”],
??????????????????????????? $row[“numpages”]);
??}elseif ($row[“type”]==”CD”){
???$product=new CdProduct($row[“name”],
????????????????????????? $row[“type”],
????????????????????????? $row[“jiage”],
????????????????????????? $row[“numpages”]);
??}
??return $product;
?}
}
//PDO部分
$dns=”sqlite://home/bob/products.db”;
$pdo=new PDO($dns,null,null);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$obj=getProduct::getInstance(1,$pdo);//调用类的静态方法

?>

自由转载,转载请注明: 转载自WEB开发笔记 www.chhua.com

本文链接地址: PHP静态方法与静态属性的使用(把纯数据转换成对象的方法) http://www.chhua.com/web-note730

相关笔记

更多