日期:2014-05-17 浏览次数:20502 次
print staticExample::$aNum; StaticExample::sayHello();
<?php /** * 静态方法和属性:通过类而不是对象来访问数据和功能 * =============注解 * 只有使用parent关键字调用方法时,才能对一个非静态方法进行静态形式调用(一个子类可以使用parent关键字访问父类,self关键字从当前类中访问静态方法或属性) */ /** * 构建shopProduct类的一个静态方法来自动实例化shopProduct对象(在上节的shopProduct类基础上增加) * @return object shopProduct对象 */ class shopProduct{ private $id=0; //上节类中的内容 //... public function setID($id){ $this->id=$id; } public static function getInstance($id, PDO $pdo){ $stmt=$pdo->prepare("select * from products where id=?"); $result=$stmt->execute(array($id)); $row=$stmt->fetch(); //实例化CD类 $product=new CDProudct($row['title'], $row['firstname'], $row['mainname'], $row['price'], $row['playlength']); $product->setId($row['id']); $product->setDiscount($row['dusciybt']); return $product; } } /* * 这样的方法有点像 工厂,可以接受原始数据或配置 据此产生对象 */ $dsn='sqlite://home/db/bob/projects/products.db'; $pdo=new PDO($dsn, null, null); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $obj=shopProduct::getInstance(1, $pdo);
abstract class shopProductWriter{ protected $products=array(); abstract public function write(); }
<?php /** * 抽象类实例 * @author lxm */ abstract class shopProductWriter{ protected $products=array(); public function addProduct(shopProduct $shopProduct){ $this->products[]=$shopProduct; } abstract public function write(); } /** * 输出XML */ class xmlProductWriter extends shopProductWriter{ public function write(){ $str='<?xml version="1.0" encoding="UTF-8"?>'."\n"; $str.="<products>\n"; foreach ($this->products as $shopProduct){ $str.="\t<product title=\"".$shopProduct->getTitle()."\">\n"; //... } $str.="</products>\n"; } }
interface Chargeable{ public function getPrice(); }
class shopProduct implements Chargeable{ //... public function getPrice(){ return ;//... } }
<?php /** * 使用拦截器 访问未定义属性时,__get()被调用 * 如果不存在什么也不做,用户试图访问的属性被解析为NULL */ class Person{ function __get($property){ $method="get".$property; if(!method_exists($this, $method)){ return $this->$method(); } } function getName(){ return "Bob"; } function getAge(){ return 24; } } $p= new Person(); print $p->name;
<?php /** * 需要把自身信息写入数据库,用析构方法在对象实例被删除时确保实例把自己保存到数据库中 */ class Person{ private $name; private $age; private $id; function __construct($name,$age){ $this->name=$name; $this->age=$age; } function setID($id){ $this->id=