Source Code Pro字體 easyphp
命名空間:隔離類和函數,php5.3以後
//test5.php
<?php namespace Test5;//命名空間必須是程序腳本的第一條語句,除了declare function test(){ echo __FILE__; }
//test6.php
<?php namespace Test6; function test(){ echo __FILE__; }
<?php
require 'test5.php'; require 'test6.php'; Test5\test(); Test6\test();
類自動載入:php5.2以後
spl_autoload_register('autoload1'); Test5::test(); Test6::test(); function autoload1($class){ require __DIR__.'/'.$class.'.php'; }
PSR-0規范:
開發符合PSR-0規范的基礎框架
spl標准庫:
PHP鏈式操作:
<?php namespace Baobab; class Database{ function where($where){ return $this; } function order($order) { return $this; } function limit($limit){ return $this; } } ?>
//index.php
$db = new Baobab\Database();
$db->where('id = 1')->order('order by id')->limit(1);
魔術方法:
object.php
<?php namespace Baobab; class Object{ protected $array = array(); function __set($key, $value){ $this->array[$key] = $value; } function __get($key){ //echo __METHOD__; return $this->array[$key]; } function __call($func, $param){ //var_dump($func,$param); return 'magic function'; } static function __callstatic($func, $param) { //var_dump($func, $param); return 'magic static function'; } function __toString(){ return __CLASS__; } function __invoke($param) { return var_dump($param); } }
index.php
$obj = new baobab\Object(); $obj->title = 'hello'; echo $obj->title; echo $obj->test1('hello', 123); echo $obj::test1('hello1', 1234); echo $obj; echo $obj('test1');
1、三種基本設計模式
Factory.php
<?php namespace Baobab; class Factory{ static function createDatabase(){ $db = new Database(); return $db; } }
index.php
$db = Baobab\Factory::createDatabase();
$db1 = Baobab\Factory::createDatabase();
$db->limit($limit);
Database.php
<?php namespace Baobab; class Database{ protected static $db; private function __construct(){ } static function getInstance(){ if (self::$db){ return self::$db; }else{ //self是指向類本身,也就是self是不指向任何已經實例化的對象(::域運算符號) self::$db = new self(); return self::$db; } }
index.php
$db = Baobab\Database::getInstance();
Register.php
<?php namespace Baobab; class Register{ protected static $objects; static function set($alias, $object){ self::$objects[$alias] = $object; } static function _unset($alias) { unset(self::$objects[$alias]); } static function get($name) { return self::$objects[$name]; } }
//將db注冊到注冊樹上 Register::set('db1', $db);
index.php
$db = Baobab\Register::get('db1');