PHP - 信用卡卡号算法函数

可以使用以下PHP函数
验证一个卡号是否是信用卡

function

validateCard
(
$cardnumber
)


{

    

$cardnumber
=
preg_replace
(
"
/\D|\s/
"
,
""
,
$cardnumber
)

# strip any non-digits

    

$cardlength
=
strlen
(
$cardnumber
)
;
    

if

(
$cardlength
!=
0
)

    

{

        

$parity
=
$cardlength
%
2
;
        

$sum
=
0
;
        

for

(
$i
=
0
;
$i
<
$cardlength
;
$i
++
)

        

{

            

$digit
=
$cardnumber
[
$i
]
;
            

if

(
$i
%
2
==
$parity
)

$digit
=
$digit
*
2
;
                

if

(
$digit
>
9
)

$digit
=
$digit
-
9
;
                    

$sum
=
$sum
+
$digit
;
        

}

        

$valid
=
(
$sum
%
10
==
0
)
;
        

return

$valid
;
    

}

    

return

false
;

}

php利用curl获取指定IP的所有信息的API

看马:

<?php
function getIpInfo($ip,$timeout=15) {
    if(!function_exists('curl_init') or !function_exists('simplexml_load_string')) return false;
    $ch = curl_init("http://ipinfodb.com/ip_query2.php?ip={$ip}&timezone=true");
    $options = array(
        CURLOPT_RETURNTRANSFER => true,
    );
    curl_setopt_array($ch,$options);
    $res = curl_exec($ch);
    curl_close($ch);
    if($xml = simplexml_load_string($res)) {
        $dt = array();
        foreach ($xml->Location->children() as $key=>$item)  {
            $dt[$key] = strtolower($item);
        }
        return $dt;
    } else {
        return false;
    }
}
$current_Ip_Info = getIpInfo('61.164.140.55');
var_dump($current_Ip_Info); 

/*
返回内容:

array(13) {
  ["Ip"]=>
  string(13) "61.164.140.55"
  ["Status"]=>
  string(2) "ok"
  ["CountryCode"]=>
  string(2) "cn"
  ["CountryName"]=>
  string(5) "china"
  ["RegionCode"]=>
  string(2) "02"
  ["RegionName"]=>
  string(8) "zhejiang"
  ["City"]=>
  string(5) "ruian"
  ["ZipPostalCode"]=>
  string(0) ""
  ["Latitude"]=>
  string(7) "27.7814"
  ["Longitude"]=>
  string(7) "120.628"
  ["TimezoneName"]=>
  string(14) "asia/chongqing"
  ["Gmtoffset"]=>
  string(5) "28800"
  ["Isdst"]=>
  string(1) "0"
}
*/
?>

很方便~~

标签: return, array, 内容, curl

php产生全球唯一标识符guid的算法一例

 

 

类库

<?php

// guid.php

class System {

  function currentTimeMillis() {

    list($usec, $sec) = explode(" ",microtime());

    return $sec.substr($usec, 2, 3);

  }

}

 

class NetAddress {

  var $name = 'localhost';

  var $ip   = '127.0.0.1';

  function getHost($coumputer_name, $ip) { // static

    $address = new NetAddress();

    $address->name = $coumputer_name;

    $address->ip   = $ip;

 

    return $address;

  }

 

  function toString() {

    return strtolower($this->name.'/'.$this->ip);

  }

}

 

class Random {

  function nextLong() {

    $tmp = rand(0,1)?'-':'';

    return $tmp.rand(1000, 9999).rand(1000, 9999).rand(1000, 9999).rand(100, 999).rand(100, 999);

  }

}

 

class Guid{

  var $valueBeforeMD5;

  var $valueAfterMD5;

  function Guid($computer_name, $ip){

    $this->getGuid($computer_name, $ip);

  }

 

  function getGuid($coumputer_name, $ip){

    $address = NetAddress::getHost($coumputer_name, $ip);

    $this->valueBeforeMD5 = $address->toString().':'.System::currentTimeMillis().':'.Random::nextLong();

    $this->valueAfterMD5 = md5($this->valueBeforeMD5);

  }

  

  function newGuid() {

   $Guid = new Guid();

   return $Guid;

  }

 

  function toString() {

   $raw = strtoupper($this->valueAfterMD5);

   return substr($raw,0,8).'-'.substr($raw,8,4).'-'.substr($raw,12,4).'-'.substr($raw,16,4).'-'.substr($raw,20);

  }

}

?>

 

调用

<?php

require_once('guid.php');

$computer_name = $_SERVER["SERVER_NAME"];

$ip            = $_SERVER["SERVER_ADDR"];

$guid = new Guid($computer_name, $ip);

print $guid->toString();

//调用产生的结果可能如: 3238D32E-807C-B1C4-01C4-FD1346D32110

使用jquery插件测试url链接是否有效及js ping url

jquery的ping插件://要用的需要明白代码及自己改些地方

(function($) {
    $.fn.ping = function(options) {
        var opts = $.extend({}, $.fn.ping.defaults, options);
        var stime = new Date().getTime();
        return this.each(function() {
            var ping, requestTime, responseTime ;
            var target = $(this);
            function ping(){
                $.ajax({url: opts.getUrl(target.html())+'/'+ Math.random() + '.html',  //设置一个空的ajax请求
                    type: opts.type,
                    dataType: 'html',
                    timeout: opts.timeout,
                    beforeSend : function() {
                        requestTime = new Date().getTime();
                    },
                    complete : function() {
                        responseTime = new Date().getTime();
                        ping = Math.abs(requestTime - responseTime);
                        $('#'+target.html().replace('.','_')).text(ping + opts.unit);
                        //target.text(ping + opts.unit);
                    }
                });
            }
            var etime = new Date().getTime();
            if(Math.abs(stime - etime)<opts.timeout){
                ping();  //无论如何都要执行一次
                opts.interval != 0 && setInterval(ping,opts.interval * 1000);
            }
        });
    };
    $.fn.ping.defaults = {
        type: 'GET',
        timeout: 10000,
        interval: 3,
        unit: 'ms',
        isUrl:function(url){    //验证url是否有效
           var strReg = "^((https|http)?://)?"
            + "(([0-9]{1,3}.){3}[0-9]{1,3}" //
            + "|" //
            + "([0-9a-z_!~*'()-]+.)*" //
            + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." //
            + "[a-z]{2,6})" //
            + "(:[0-9]{1,4})?" //
            + "((/?)|" //
            + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
            var re=new RegExp(strReg);
            return re.test(url);
           },
        getUrl:function(url){    //保证url带http://
            var strReg="^((https|http)?://){1}"
            var re=new RegExp(strReg);
            return re.test(url)?url:"http://"+url;
        }
    };
})(jQuery);

 

js ping url:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>HTTP Ping</title>
<style>
html{height: 100%;overflow: hidden;}
body{background: #000;color: #C0C0C0;font-weight: bold;font-size: 14px;font-family: Lucida Console;height: 100%;margin: 0 0 0 5px;}
#divInput{height: 10%;}
#divContent{height: 90%;overflow: auto;}
#txtTimeout{width: 40px;}
button{    margin-left: 10px;}
</style>
</head>
<body>
<div id="divInput">
    <span>URL:</span>
    <input id="txtURL" type="text" />
    <span>Timeout:</span>
    <input id="txtTimeout" type="text" value="2000" />
    <input id="btnSwitch" type="button" value="Start" onclick="handleBtnClick()" />
    <hr/>
</div>
<div id="divContent"></div>
<script>
var intStartTime;
var objIMG = new Image();
objIMG.onload =
objIMG.onerror =
function(){
    /*
     * 有回应,取消超时计时
     */
    clearTimeout(intTimerID);
    if(!bolIsRunning || bolIsTimeout)
        return;
    var delay = new Date() - intStartTime;
    println("Reply from " +
            strURL +
            " time" +
            ((delay<1)?("<1"):("="+delay)) +
            "ms");
    arrDelays.push(delay);
    /*
     * 每次请求间隔限制在1秒以上
     */
    setTimeout(ping, delay<1000?(1000-delay):1000);
}
function ping(){
    /*
     * 发送请求
     */
    intStartTime = +new Date();
    intSent++;
    objIMG.src = strURL + "/" + intStartTime;
    bolIsTimeout = false;
    /*
     * 超时计时
     */
    intTimerID = setTimeout(timeout, intTimeout);
}
function timeout(){
    if(!bolIsRunning)
        return;
    bolIsTimeout = true;
    objIMG.src = "X:\\";
    println("Request timed out.");
    ping();
}
</script>
<script>
var $ = function(v){return document.getElementById(v)};
var arrDelays = [];
var intSent;
var bolIsRunning = false;
var bolIsTimeout;
var strURL;
var intTimeout;
var intTimerID;
var objBtn = $("btnSwitch");
var objContent = $("divContent");
var objTxtURL = $("txtURL");
objTxtURL.value = window.location.host;
function handleBtnClick(){
    if(bolIsRunning){
        /*
         * 停止
         */
        var intRecv = arrDelays.length;
        var intLost = intSent-intRecv;
        var sum = 0;
        for(var i=0; i<intRecv; i++)
            sum += arrDelays[i];
        objBtn.value = "Start";
        bolIsRunning = false;
        /*
         * 统计结果
         */
        println(" ");
        println("Ping statistics for " + strURL + ":");
        println("  Packets: Sent = " +
                intSent +
                ", Received = " +
                intRecv +
                ", Lost = " +
                intLost +
                " (" +
                Math.floor(intLost / intSent * 100) +
                "% loss),");
        if(intRecv == 0)
            return;
        println("Approximate round trip times in milli-seconds:");
        println("  Minimum = " +
                Math.min.apply(this, arrDelays) +
                "ms, Maximum = " +
                Math.max.apply(this, arrDelays) +
                "ms, Average = " +
                Math.floor(sum/intRecv) +
                "ms");
    }else{
        /*
         * 开始
         */
        strURL = objTxtURL.value;
        if(strURL.length == 0)
            return;
        if(strURL.substring(0,7).toLowerCase() != "http://")
            strURL = "http://" + strURL;
        intTimeout = parseInt($("txtTimeout").value, 10);
        if(isNaN(intTimeout))
            intTimeout = 2000;
        if(intTimeout < 1000)
            intTimeout = 1000;
        objBtn.value = "Stop ";
        bolIsRunning = true;
        arrDelays = [];
        intSent = 0;
        cls();
        println("Pinging " + strURL + ":");
        println(" ");
        ping();
    }
}
function println(str){
    var objDIV = document.createElement("div");
    if(objDIV.innerText != null)
        objDIV.innerText = str;
    else
        objDIV.textContent = str;
    objContent.appendChild(objDIV);
    objContent.scrollTop = objContent.scrollHeight;
}
function cls(){
    objContent.innerHTML = "";
}
</script>
</body>
</html>

标签: url, function, var, return, ping

兼容ie FF 多浏览器的js复制代码

MD,找了半天,总算一个比较满意的··     对于火狐,如果浏览器设置没打开,那会麻烦点。

 

function copyToClipboard(txt) { 
     if(window.clipboardData) { 
             window.clipboardData.clearData(); 
             window.clipboardData.setData("Text", txt); 
     } else if(navigator.userAgent.indexOf("Opera") != -1) { 
          window.location = txt; 
     } else if (window.netscape) { 
          try { 
               netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
          } catch (e) { 
               alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'"); 
          } 
          var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 
          if (!clip) 
               return; 
          var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
          if (!trans) 
               return; 
          trans.addDataFlavor('text/unicode'); 
          var str = new Object(); 
          var len = new Object(); 
          var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 
          var copytext = txt; 
          str.data = copytext; 
          trans.setTransferData("text/unicode",str,copytext.length*2); 
          var clipid = Components.interfaces.nsIClipboard; 
          if (!clip) 
               return false; 
          clip.setData(trans,null,clipid.kGlobalClipboard); 
     } 
  alert("复制成功!") ;
}

《Head First 设计模式》php设计模式版

策略模式

 

<?php
/**
 * 策略模式
 * 定义了算法族,分别封装起来,让它们之间可以互相替换,
 * 此模式让算法的变化独立于使用算法的客户。
 */
//飞行行为接口
interface FlyBehavior {
    public function fly();
}
//呱呱叫行为接口
interface QuackBehavior {
    public function quack();
}
//翅膀飞行
class FlyWithWings implements FlyBehavior {
    public function fly() {
        echo "I'm flying!!\n";
    }
}
//不会飞
class FlyNoWay implements FlyBehavior {
    public function fly() {
        echo "I can't fly!\n";
    }
}
class FlyRocketPowered implements FlyBehavior {
    public function fly() {
        echo "I'm flying with a rocket!\n";
    }
}
class Qquack implements QuackBehavior {
    public function quack() {
        echo "Quack\n";
    }
}
class Squeak implements QuackBehavior {
    public function quack() {
        echo "Squeak\n";
    }
}
class MuteQuack implements QuackBehavior {
    public function quack() {
        echo "<< Silence >>\n";
    }
}
abstract class Duck {
    protected $quack_obj;
    protected $fly_obj;
    public abstract function display();

    public function performQuack() {
        $this->quack_obj->quack();
    }
    public function performFly() {
        $this->fly_obj->fly();
    }
    public function swim() {
        echo "All ducks float, even decoys!\n";
    }
    public function setFlyBehavior(FlyBehavior $fb) {
        $this->fly_obj = $fb;
    }
    public function setQuackBehavior(QuackBehavior $qb) {
        $this->quack_obj = $qb;
    }
}

class ModelDuck extends Duck {
    public function __construct() {
        $this->fly_obj = new FlyNoWay();
        $this->quack_obj = new MuteQuack();
    }
    public function display() {
        echo "I'm a model duck!\n";
    }
}

$model = new ModelDuck();
$model->performFly();
$model->performQuack();
//提供新的能力
$model->setFlyBehavior(new FlyRocketPowered());
$model->setQuackBehavior(new Squeak());
$model->performFly();
$model->performQuack();

?>

 

单件模式

 

<?php
/**
 * 单件模式
 * 确保一个类只有一个实例,并提供一个全局访问点。
 */
class MyClass {
    private static $uniqueInstance;
    private function __construct() {

    }
    public static function getInstance() {
        if (self::$uniqueInstance == null) {
            self::$uniqueInstance = new MyClass();
        }
        return self::$uniqueInstance;
    }
}
$myClass = MyClass::getInstance();
var_dump($myClass);
$myClass = MyClass::getInstance();
var_dump($myClass);
?>

 

工厂方法模式

 

<?php
abstract class PizzaStore {
    public function orderPizza($type) {
        $pizza = $this->createPizza($type);

        $pizza->prepare();
        $pizza->bake();
        $pizza->cut();
        $pizza->box();
        return $pizza;
    }

    public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new NYStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new NYStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new NYStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new NYStylePapperoniPizza();
        } else {
            return null;

        }
    }
}
class ChicagoPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new ChicagoStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new ChicagoStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new ChicagoStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new ChicagoStylePapperoniPizza();
        } else {
            return null;
        }
    }
}
abstract class Pizza {
    public $name;
    public $dough;
    public $sauce;
    public $toppings = array();

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        echo "Yossing dough...\n";
        echo "Adding sauce...\n";
        echo "Adding toppings: \n";
        for ($i = 0; $i < count($this->toppings); $i++) {
            echo "    " . $this->toppings[$i] . "\n";
        }
    }

    public function bake() {
        echo "Bake for 25 minutes at 350\n";
    }

    public function cut() {
        echo "Cutting the pizza into diagonal slices\n";
    }

    public function box() {
        echo "Place pizza in official PizzaStore box\n";
    }

    public function getName() {
        return $this->name;
    }
}

class NYStyleCheesePizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and cheese Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano Cheese";
    }
}

class NYStyleVeggiePizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and veggie Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano veggie";
    }
}
class NYStyleClamPizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and clam Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano clam";
    }
}
class NYStylePapperoniPizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and papperoni Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano papperoni";
    }
}

class ChicagoStyleCheesePizza extends Pizza {
    public function __construct() {
        $this->name = "Chicago Style Deep Dish Cheese Pizza";
        $this->dough = "Extra Thick Crust Dough";
        $this->sauce = "Plum Tomato Sauce";

        $this->toppings[] = "Shredded Mozzarella Cheese";
    }

    public function cut() {
        echo "Cutting the pizza into square slices\n";
    }
}

$myStore = new NYPizzaStore();
$chicagoStore = new ChicagoPizzaStore();
$pizza = $myStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

$pizza = $chicagoStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

?>

 

工厂模式

 

<?php
abstract class PizzaStore {
    public function orderPizza($type) {
        $pizza = $this->createPizza($type);

        $pizza->prepare();
        $pizza->bake();
        $pizza->cut();
        $pizza->box();
        return $pizza;
    }

    public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
    public function createPizza($type) {
        $pizza = null;
        $ingredientFactory = new NYPizzaIngredientFactory();
        if ($type == "cheese") {
            $pizza = new CheesePizza($ingredientFactory);
            $pizza->setName('New York Style Cheese Pizza');
        } elseif ($type == "veggie") {
            $pizza = new VeggiePizza($ingredientFactory);
            $pizza->setName('New York Style Veggie Pizza');
        } elseif ($type == "clam") {
            $pizza = new ClamPizza($ingredientFactory);
            $pizza->setName('New York Style Clam Pizza');
        } elseif ($type == "papperoni") {
            $pizza = new PapperoniPizza($ingredientFactory);
            $pizza->setName('New York Style Papperoni Pizza');
        }
        return $pizza;
    }
}
class ChicagoPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new ChicagoStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new ChicagoStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new ChicagoStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new ChicagoStylePapperoniPizza();
        } else {
            return null;
        }
    }
}
interface PizzaIngredientFactory {
    public function createDough();
    public function createSauce();
    public function createCheese();
    public function createVeggies();
    public function createPepperoni();
    public function createClam();
}
class NYPizzaIngredientFactory implements PizzaIngredientFactory {
    public function createDough() {
        return new ThinCrustDough();
    }
    public function createSauce() {
        return new MarinaraSauce();
    }
    public function createCheese() {
        return new ReggianoCheese();
    }
    public function createVeggies() {
        $veggies = array(
        new Garlic(),
        new Onion(),
        new Mushroom(),
        new RedPepper(),
        );
        return $veggies;
    }
    public function createPepperoni() {
        return new SlicedPepperoni();
    }
    public function createClam() {
        return new FreshClams();
    }
}
class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
    public function createDough() {
        return new ThickCrustDough();
    }
    public function createSauce() {
        return new PlumTomatoSauce();
    }
    public function createCheese() {
        return new Mozzarella();
    }
    public function createVeggies() {
        $veggies = array(
        new BlackOlives(),
        new Spinach(),
        new EggPlant(),
        );
        return $veggies;
    }
    public function createPepperoni() {
        return new SlicedPepperoni();
    }
    public function createClam() {
        return new FrozenClams();
    }
}
abstract class Pizza {
    public $name;
    public $dough;
    public $sauce;
    public $veggies = array();
    public $cheese;
    public $pepperoni;
    public $clam;

    public abstract function prepare();

    public function bake() {
        echo "Bake for 25 minutes at 350\n";
    }

    public function cut() {
        echo "Cutting the pizza into diagonal slices\n";
    }

    public function box() {
        echo "Place pizza in official PizzaStore box\n";
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function __toString() {

    }
}

class CheesePizza extends Pizza {
    public $ingredientFactory;

    public function __construct(PizzaIngredientFactory $ingredientFactory) {
        $this->ingredientFactory = $ingredientFactory;
    }

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        $this->dough = $this->ingredientFactory->createDough();
        $this->sauce = $this->ingredientFactory->createSauce();
        $this->cheese = $this->ingredientFactory->createCheese();
    }
}

class ClamPizza extends Pizza {
    public $ingredientFactory;

    public function __construct(PizzaIngredientFactory $ingredientFactory) {
        $this->ingredientFactory = $ingredientFactory;
    }

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        $this->dough = $this->ingredientFactory->createDough();
        $this->sauce = $this->ingredientFactory->createSauce();
        $this->cheese = $this->ingredientFactory->createCheese();
        $clam = $this->ingredientFactory->createClam();
    }
}

$nyPizzaStore = new NYPizzaStore();
$nyPizzaStore->orderPizza('cheese');
?>

 

观察者模式

 

<?php
/**
 * 观察者模式
 * 定义了对象之间的一对多依赖,当一个对象改变状态时,
 * 它的所有依赖者都会收到通知并自动更新。
 */
interface Subject {
    public function registerObserver(Observer $o);
    public function removeObserver(Observer $o);
    public function notifyObservers();
}
interface Observer {
    public function update($temperature, $humidity, $pressure);
}
interface DisplayElement {
    public function display();
}
class WeatherData implements Subject {
    private $observers = array();
    private $temperature;
    private $humidity;
    private $pressure;
    public function __construct() {
        $this->observers = array();
    }
    public function registerObserver(Observer $o) {
        $this->observers[] = $o;
    }
    public function removeObserver(Observer $o) {
        if (($key = array_search($o, $this->observers)) !== false) {
            unset($this->observers[$key]);
        }
    }
    public function notifyObservers() {
        foreach ($this->observers as $observer) {
            $observer->update($this->temperature, $this->humidity, $this->pressure);
        }
    }
    public function measurementsChanged() {
        $this->notifyObservers();
    }
    public function setMeasurements($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->pressure = $pressure;
        $this->measurementsChanged();
    }
}
class CurrentConditionsDisplay implements Observer, DisplayElement {
    private $temperature;
    private $humidity;
    private $weatherData;
    public function __construct(Subject $weatherData) {
        $this->weatherData = $weatherData;
        $weatherData->registerObserver($this);
    }
    public function update($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->display();
    }
    public function display() {
        echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%\n";
    }
}
class StatistionsDisplay implements Observer, DisplayElement {
    private $temperature;
    private $humidity;
    private $pressure;
    private $weatherData;
    public function __construct(Subject $weatherData) {
        $this->weatherData = $weatherData;
        $weatherData->registerObserver($this);
    }
    public function update($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->pressure = $pressure;
        $this->display();
    }
    public function display() {
        echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%; 气压:" . $this->pressure . "\n";
    }
}
$weatherData = new WeatherData();
$currentDisplay = new CurrentConditionsDisplay($weatherData);
$statistionDisplay = new StatistionsDisplay($weatherData);
$weatherData->setMeasurements(10, 20, 30);
$weatherData->removeObserver($currentDisplay);
$weatherData->setMeasurements(30, 40, 50);
?>

 

命令模式

 

<?php

class Light {
    public function __construct() {

    }

    public function on() {
        echo "Light On\n";
    }

    public function off() {
        echo "Light Off\n";
    }
}

interface Command {
    public function execute();
}

class LightOnCommand implements Command {
    public $light;

    public function __construct(Light $light) {
        $this->light = $light;
    }

    public function execute() {
        $this->light->on();
    }
}

class SimpleRemoteControl {
    public $slot;

    public function __construct() {

    }

    public function setCommand(Command $command) {
        $this->slot = $command;
    }

    public function buttonWasPressed() {
        $this->slot->execute();
    }
}

class RemoteControlTest {
    public static function main() {
        $remote = new SimpleRemoteControl();
        $light = new Light();
        $lightOn = new LightOnCommand($light);
        $remote->setCommand($lightOn);
        $remote->buttonWasPressed();
    }
}

RemoteControlTest::main();

?>

 

装饰者模式

 

<?php
/**
* 装饰着模式
* 动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
*/
abstract class Beverage {
public $description = "Unknown Beverage";

public function getDescription() {
return $this->description;
}

public abstract function cost();
}

abstract class CondimentDecorator extends Beverage {
//JAVA代码里这里是个抽象类,PHP不允许这么做
public function getDescription() {
return $this->description;
}
}

class Espresso extends Beverage {
public function __construct() {
$this->description = "Espresso";
}

public function cost() {
return 1.99;
}
}

class HouseBlend extends Beverage {
public function __construct() {
$this->description = "HouseBlend";
}

public function cost() {
return .89;
}
}

class DarkRoast extends Beverage {
public function __construct() {
$this->description = "DarkRoast";
}

public function cost() {
return .99;
}
}

class Mocha extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Mocha";
}
public function cost() {
return .20 + $this->beverage->cost();
}
}

class Whip extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Whip";
}
public function cost() {
return .10 + $this->beverage->cost();
}
}

class Soy extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Soy";
}
public function cost() {
return .15 + $this->beverage->cost();
}
}

$beverage = new Espresso();
echo $beverage->getDescription() . "\n";
$beverage2 = new DarkRoast();
$beverage2 = new Mocha($beverage2);
$beverage2 = new Mocha($beverage2);
$beverage2 = new Whip($beverage2);
echo $beverage2->getDescription() . " $" . $beverage2->cost() . "\n";

$beverage3 = new HouseBlend();
$beverage3 = new Soy($beverage3);
$beverage3 = new Mocha($beverage3);
$beverage3 = new Whip($beverage3);
echo $beverage3->getDescription() . " $" . $beverage3->cost() . "\n";
?>

状态模式

 

<?php

class GumballMachine {
const SOLD_OUT = 0;
const NO_QUARTER = 1;
const HAS_QUARTER = 2;
const SOLD = 3;

public $state = self::SOLD_OUT;
public $count = 0;

public function __construct($count) {
$this->count = $count;
if ($count > 0) {
$this->state = self::NO_QUARTER;
}
}

public function insertQuarter() {
if ($this->state == self::HAS_QUARTER) {
echo "You can't insert another quarter!\n";
} else if ($this->state == self::NO_QUARTER) {
$this->state = self::HAS_QUARTER;
echo "You inserted a quarter!\n";
} else if ($this->state == self::SOLD_OUT) {
echo "You can't insert a quarter, the machine is sold out!\n";
} else if ($this->state == self::SOLD) {
echo "Please wait, we're already giving you a gumball!\n";
}
}
}

$obj = new GumballMachine(0);
print_r($obj)

?>