>  기사  >  백엔드 개발  >  PHP에서 클로저 사용

PHP에서 클로저 사용

WBOY
WBOY원래의
2016-07-29 09:14:47913검색

PHP에서 클로저 사용

예제 1

<code><span><?php</span><span>/**
 * 代码中有一个Di容器用来保存<strong>对象</strong>实例,然后通过set()方法注册服务,通过get()方法获取服务。
 * 我们看到$di->set()的时候,使用了匿名函数,我们预先注册了zhangsan和lisi两个服务,这两个服务都是User类的实例,
 * 在$di->set的时候实际上并没有实例化,而是在$di->get()的时候才执行了匿名函数并将<strong>对象</strong>返回,
 * 这就实现了**按需实例化,不用则不实例化,提高效率**。
 */</span><span><span>class</span><span>Di</span> {</span><span>private</span><span>$_factory</span>;

    <span>public</span><span><span>function</span><span>set</span><span>(<span>$id</span>, <span>$value</span>)</span> {</span><span>$this</span>->_factory[<span>$id</span>] = <span>$value</span>;
    }

    <span>public</span><span><span>function</span><span>get</span><span>(<span>$id</span>)</span> {</span><span>$value</span> = <span>$this</span>->_factory[<span>$id</span>];
        <span>return</span><span>$value</span>();
    }

}

<span><span>class</span><span>User</span> {</span><span>private</span><span>$_username</span>;

    <span><span>function</span><span>__construct</span><span>(<span>$username</span> = <span>""</span>)</span> {</span><span>$this</span>->_username = <span>$username</span>;
    }

    <span><span>function</span><span>getUserName</span><span>()</span> {</span><span>return</span><span>$this</span>->_username;
    }

}

<span>//从这里开始看</span><span>$di</span> = <span>new</span> Di();
<span>$di</span>->set(<span>"zhangsan"</span>, <span><span>function</span><span>()</span> {</span><span>return</span><span>new</span> User(<span>'张三'</span>);
});
<span>$di</span>->set(<span>"lisi"</span>, <span><span>function</span><span>()</span> {</span><span>return</span><span>new</span> User(<span>"李四"</span>);
});
<span>echo</span><span>$di</span>->get(<span>"zhangsan"</span>)->getUserName();
<span>echo</span><span>$di</span>->get(<span>"lisi"</span>)->getUserName();</code>

예제 2

<code><span>/**
 * 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
 * 其中有一个方法用来计算购物车中所有商品的总价格。该方法使用了一个closure作为回调函数。
 */</span><span><span>class</span><span>Cart</span> {</span><span>const</span> PRICE_BUTTER = <span>1.00</span>;
    <span>const</span> PRICE_MILK = <span>3.04</span>;
    <span>const</span> PRICE_EGGS = <span>6.95</span>;

    <span>protected</span><span>$products</span> = <span>array</span>();

    <span>public</span><span><span>function</span><span>add</span><span>(<span>$product</span>, <span>$quantity</span>)</span> {</span><span>$this</span>->products[<span>$product</span>] = <span>$quantity</span>;
    }

    <span>public</span><span><span>function</span><span>getQuantity</span><span>(<span>$product</span>)</span> {</span><span>return</span><span>isset</span>(<span>$this</span>->products[<span>$product</span>]) ? <span>$this</span>->products[<span>$product</span>] : <span>FALSE</span>;
    }

    <span>public</span><span><span>function</span><span>getTotal</span><span>(<span>$tax</span>)</span> {</span><span>$total</span> = <span>0.00</span>;

        <span>$callback</span> = <span><span>function</span><span>(<span>$quantity</span>, <span>$product</span>)</span><span>use</span><span>(<span>$tax</span>, &<span>$total</span>)</span> {</span><span>$pricePerItem</span> = constant(<span>__CLASS__</span> . <span>"::PRICE_"</span> . strtoupper(<span>$product</span>));
            <span>$total</span> += (<span>$pricePerItem</span> * <span>$quantity</span>) * (<span>$tax</span> + <span>1.0</span>);
        };

        array_walk(<span>$this</span>->products, <span>$callback</span>);
        <span>return</span> round(<span>$total</span>, <span>2</span>);
    }

}

<span>$my_cart</span> = <span>new</span> Cart;

<span>// 往购物车里添加条目</span><span>$my_cart</span>->add(<span>'butter'</span>, <span>1</span>);
<span>$my_cart</span>->add(<span>'milk'</span>, <span>3</span>);
<span>$my_cart</span>->add(<span>'eggs'</span>, <span>6</span>);

<span>// 打出出总价格,其中有 5% 的销售税.</span><span>print</span><span>$my_cart</span>->getTotal(<span>0.05</span>) . <span>"\n"</span>;

<span>// The result is 54.29</span></code>

위에서는 PHP의 클로저 사용에 대해 소개했으며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.