Home >类库下载 >PHP类库 >A little PHP trick

A little PHP trick

高洛峰
高洛峰Original
2016-10-20 13:49:571146browse

How to realize that when a time-consuming function or class method is called multiple times, the operation is performed for the first time, and the result is returned directly when the function is called again?

<?php 

class MyDate
{
    public static function getCurrentDate()
    {
        static $current_date = &#39;&#39;;

        if (!$current_date) {
            echo &#39;only run one time&#39;;
            usleep(200000);
            $current_date  = date(&#39;Y-m-d H:i:s&#39;);
        }

        return $current_date;
    }

    public static function getCurrentDate2()
    {
        usleep(200000);
        echo &#39;run everytime&#39;;
        return date(&#39;Y-m-d H:i:s&#39;);
    }
}

$start = microtime(true);
$i = 5;
while ($i--) {
    MyDate::getCurrentDate();
}
echo microtime(true) - $start;    //200ms

$start = microtime(true);
$i = 5;
while ($i--) {
    MyDate::getCurrentDate2();
}
echo microtime(true) - $start;    //1s


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more