php一些常用函数

<?php

//php嗣脯杅郪睿勤砓腔蛌遙
function object_to_array($arr)
{
    if (is_object($arr)) {
        $arr = get_object_vars($arr);
    }

    if (is_array($arr)) {
        return array_map(__FUNCTION__, $arr);
    } else {
        return $arr;
    }
}

function array_to_object($arr)
{
    if (is_array($arr)) {
        return (object) array_map(__FUNCTION__, $arr);
    } else {
        return $arr;
    }
}

//菰寥源宒腔勤曹講笢腔杻忷趼睫輛俴蛌砱
function addslashes_deep($value)
{
    if (empty($value)) {
        return $value;
    } else {
        return is_array($value) ? array_map(‘addslashes_deep‘, $value) : addslashes($value);
    }
}

/**
 * 殿隙蚕勤砓扽俶郪傖腔壽薊杅郪
 */
function get_object_vars_deep($obj)
{
    if (is_object($obj)){
        $obj = get_object_vars($obj);
    }
    if (is_array($obj)) {
        foreach ($obj as $key => $value) {
            $obj[$key] = get_object_vars_deep($value);
        }
    }
    return $obj;
}

/*斐膘砉涴欴腔脤戙: "IN(‘a‘,‘b‘)";
* * @param    mix      $item_list      蹈桶杅郪麼趼睫揹,?彆峈趼睫揹奀,趼睫揹硐諉忳杅趼揹
 * @param    string   $field_name     趼僇靡備
*/
function db_create_in($item_list, $field_name = ‘‘)
{
    if (empty($item_list)) {
        return $field_name . " IN (‘‘) ";
    } else {
        if (!is_array($item_list)) {
            $item_list = explode(‘,‘, $item_list);
            foreach ($item_list as $k => $v) {
                $item_list[$k] = intval($v);
            }
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = ‘‘;
        foreach ($item_list as $item) {
            if ($item !== ‘‘) {
                $item_list_tmp .= $item_list_tmp ? ",‘$item‘" : "‘$item‘";
            }
        }
        if (empty($item_list_tmp)) {
            return $field_name . " IN (‘‘) ";
        } else {
            return $field_name . ‘ IN (‘ . $item_list_tmp . ‘) ‘;
        }
    }
}

/**
 * 蚚CURL懂杸測賸file_get_contentsㄛ價衾假?睿俶夔蕉藉ㄛ壽敕allow_url_fopen
 * @param $durl
 */
function curl_file_get_contents($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
    curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

/**
 * 刉壺恅璃標
 * @param $dir 恅璃標繚噤
 */
function rm_dir($dir)
{
    if (is_file($dir)) { //岆恅璃ㄛ眻諉刉壺
        chmod($dir, 0777);
        @unlink($dir);
        return true;
    } elseif (is_dir($dir)) {
        if ($path = opendir($dir)) { //紨跺刉壺恅璃麼恅璃標
            while ($file = readdir($path)) {
                if (($file == ‘.‘) || ($file == ‘..‘)) {
                    continue;
                }
                //菰寥刉壺赽恅璃標
                chmod($dir . ‘/‘ . $file, 0777);
                rm_dir($dir . ‘/‘ . $file);
            }
            closedir($path);
            chmod($dir, 0777);
            rmdir($dir); //刉壺恅璃標
            return true;
        }
    }
    return false;
}

/**
 * 蕭探恅璃標
 * @param  $from 恅璃標繚噤麼恅璃
 * @param $to_dir 恅璃標繚噤
 */
function copy_dir($from, $to_dir)
{
    if (!ecm_mkdir($to_dir)) { //醴梓祥岆恅璃標
        return false;
    }
    if (is_file($from)) {
        @copy($from, $to_dir);
        return true;
    } elseif (is_dir($from)) {
        if ($path = opendir($from)) { //紨跺葩秶恅璃麼恅璃標
            while ($file = readdir($path)) {
                if (($file == ‘.‘) || ($file == ‘..‘)) {
                    continue;
                }
                if (is_dir($from . ‘/‘ . $file)) { //菰寥葩秶恅璃標
                    copy_dir($from . ‘/‘ . $file, $to_dir . ‘/‘ . $file);
                } elseif (is_file($from . ‘/‘ . $file)) { //葩秶恅璃
                    copy($from . ‘/‘ . $file, $to_dir . ‘/‘ . $file);
                }
            }
            closedir($path);
            return true;
        }
    }
    return false;
}

/**
 * 斐膘醴翹ㄗ?彆蜆醴翹腔奻撰醴翹祥湔婓ㄛ頗珂斐膘奻撰醴翹ㄘ
 * 甡懇衾 ROOT_PATH 都講ㄛブ硐夔斐膘 ROOT_PATH 醴翹狟腔醴翹
 * 醴翹煦路睫斛剕岆 / 祥夔岆  *
 * @param   string  $absolute_path  橈勤繚噤
 * @param   int     $mode           醴翹?癹
 * @return  bool
 */
function ecm_mkdir($absolute_path, $mode = 0777)
{
    if (is_dir($absolute_path)) {
        return true;
    }
    $root_path = ROOT_PATH;
    $relative_path = str_replace($root_path, ‘‘, $absolute_path);
    $each_path = explode(‘/‘, $relative_path);
    $cur_path = $root_path; // 絞ゴ悜遠揭燴腔繚噤
    foreach ($each_path as $path) {
        if ($path) {
            $cur_path = $cur_path . ‘/‘ . $path;
            if (!is_dir($cur_path)) {
                if (@mkdir($cur_path, $mode)) {
                    fclose(fopen($cur_path . ‘/index.htm‘, ‘w‘));//汜傖忑珜
                } else {
                    return false;
                }
            }
        }
    }
    return true;
}

 /*
 * Make a error message by JSON format utf-8
 *
 * @param   string  $msg
 */
function json_error($msg = ‘‘, $retval = null, $jqremote = false)
{
    //登录
    if ($msg == ‘login_please‘) {
        echo ‘<script language="javascript"> window.top.history.go(0);</script>‘;
        return;
    }

    $result = array(
        ‘done‘ => false,
        ‘msg‘ => $msg
    );
    if (isset($retval)) {
        $result[‘retval‘] = $retval;
    }
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header("Content-type:text/plain;charset=utf-8", true);
    $json = json_encode($result);
    if ($jqremote === false) {
        $jqremote = isset($_GET[‘jsoncallback‘]) ? trim($_GET[‘jsoncallback‘]) : false;
    }
    if ($jqremote) {
        $json = $jqremote . ‘(‘ . $json . ‘)‘;
    }
    echo $json;
}

/**
 * Make a successfully message utf-8
 *
 * @param   mixed   $retval
 * @param   string  $msg
 */
function json_result($retval = ‘‘, $msg = ‘‘, $jqremote = false)
{

    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header("Content-type:text/plain;charset=utf-8", true);
    $json = json_encode(array(
        ‘done‘ => true,
        ‘msg‘ => $msg,
        ‘retval‘ => $retval
    ));
    if ($jqremote === false) {
        $jqremote = isset($_GET[‘jsoncallback‘]) ? trim($_GET[‘jsoncallback‘]) : false;
    }
    if ($jqremote) {
        $json = $jqremote . ‘(‘ . $json . ‘)‘;
    }
    echo $json;
}

/**
 * 嗣峎杅郪齬唗
 *
 * @author Doujia
 * @param  array $array
 * @param  array $cols
 * @return array
 *
 * e.g. $data = array_msort($data, array(‘sort_order‘=>SORT_ASC, ‘add_time‘=>SORT_DESC));
 */
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) {
            $colarr[$col][‘_‘ . $k] = strtolower($row[$col]);
        }
    }
    $eval = ‘array_multisort(‘;
    foreach ($cols as $col => $order) {
        $eval .= ‘$colarr[\‘‘ . $col . ‘\‘],‘ . $order . ‘,‘;
    }
    $eval = substr($eval, 0, -1) . ‘);‘;
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k, 1);
            if (!isset($ret[$k]))
                $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;
}

/**
     *
     * strlen function
     *
     * @param string $string
     * @param bool $onlyCharacters 岆瘁硐呾艘善腔趼﹝
     * 撼瞰ㄩ※扂淩邟§ㄩ涴岆3跺趼﹝※扂T邟§ㄩ涴岆3跺趼﹝
     * 珨曆趕憩岆ㄛ笢荎恅肮欴勤渾
     *
     */
    public static function strlen($string, $onlyCharacters = false)
    {
        $strlen = 0;
        $length = strlen($string);
        $characterLength = 0;
        while ($strlen < $length) {
            $stringTMP = substr($string, $strlen, 1);
            if (ord($stringTMP) >= 224) {
                $strlen = $strlen + 3;
            } elseif (ord($stringTMP) >= 192) {
                $strlen = $strlen + 2;
            } else {
                $strlen = $strlen + 1;
            }
            $characterLength++;
        }
        return $onlyCharacters ? $characterLength : $strlen;
    }

    /**
     * 汜傖呴儂躇鎢ㄗ呴儂8弇ㄛ4弇杅趼ㄛ4弇趼譫ㄘ
     *
     * @return string
     *
     */
    public static function create_password()
    {
        $numbers = ‘1234567890‘;
        $letters = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘;
        $numbers_create = array();
        $letters_create = array();
        for ($i = 0; $i < 4; $i++) {
            $numbers_create[] = $numbers{rand(0, 9)};
            $letters_create[] = $letters{rand(0, 25)};
        }
        $arr = array_merge($numbers_create, $letters_create);
        shuffle($arr);
        return implode(‘‘, $arr);
    }

 /**
     *
     * @param type $len
     * @return type
     */
    public static function generate_code($len = 15)
    {
        $chars = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘;
        for ($i = 0, $count = strlen($chars); $i < $count; $i++) {
            $arr[$i] = $chars[$i];
        }
        mt_srand((double)microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode(‘‘, $arr), 5, $len);
        return $code;
    }

/**
     * 鳳?恅璃 mime 濬倰
     *
     * @date  2011-12-21
     */
    public static function get_mime_type ($filename)
    {
        preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
        switch (strtolower($fileSuffix[1]))
        {
            case "js":
                return "application/x-javascript";
            case "json":
                return "application/json";
            case "jpg":
            case "jpeg":
            case "jpe":
                return "image/jpeg";
            case "png":
            case "gif":
            case "bmp":
            case "tiff":
                return "image/" . strtolower($fileSuffix[1]);
            case "css":
                return "text/css";
            case "xml":
                return "application/xml";
            case "doc":
            case "docx":
                return "application/msword";
            case "xls":
            case "xlt":
            case "xlm":
            case "xld":
            case "xla":
            case "xlc":
            case "xlw":
            case "xll":
                return "application/vnd.ms-excel";
            case "ppt":
            case "pps":
                return "application/vnd.ms-powerpoint";
            case "rtf":
                return "application/rtf";
            case "pdf":
                return "application/pdf";
            case "html":
            case "htm":
            case "php":
                return "text/html";
            case "txt":
                return "text/plain";
            case "mpeg":
            case "mpg":
            case "mpe":
                return "video/mpeg";
            case "mp3":
                return "audio/mpeg3";
            case "wav":
                return "audio/wav";
            case "aiff":
            case "aif":
                return "audio/aiff";
            case "avi":
                return "video/msvideo";
            case "wmv":
                return "video/x-ms-wmv";
            case "mov":
                return "video/quicktime";
            case "rar":
                return "application/x-rar-compressed";
            case "zip":
                return "application/zip";
            case "tar":
                return "application/x-tar";
            case "swf":
                return "application/x-shockwave-flash";
            default:
                if (function_exists("mime_content_type"))
                {
                    $fileSuffix = mime_content_type($filename);
                }
                return "unknown/" . trim($fileSuffix[0], ".");
        }
    }

/**
     * 諦誧傷淩妗 IP
     */
    public static function real_ip_client ()
    {
        static $realip = NULL;
        if ($realip !== NULL)
        {
            return $realip;
        }
        if (isset($_SERVER))
        {
            if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR‘]))
            {
                $arr = explode(‘,‘, $_SERVER[‘HTTP_X_FORWARDED_FOR‘]);
                /* ?X-Forwarded-For笢菴珨跺準unknown腔衄虴IP趼睫揹 */
                foreach ($arr as $ip)
                {
                    $ip = trim($ip);
                    if ($ip != ‘unknown‘)
                    {
                        $realip = $ip;
                        break;
                    }
                }
            }
            elseif (isset($_SERVER[‘HTTP_CLIENT_IP‘]))
            {
                $realip = $_SERVER[‘HTTP_CLIENT_IP‘];
            }
            else
            {
                if (isset($_SERVER[‘REMOTE_ADDR‘]))
                {
                    $realip = $_SERVER[‘REMOTE_ADDR‘];
                }
                else
                {
                    $realip = ‘0.0.0.0‘;
                }
            }
        }
        else
        {
            if (getenv(‘HTTP_X_FORWARDED_FOR‘))
            {
                $realip = getenv(‘HTTP_X_FORWARDED_FOR‘);
            }
            elseif (getenv(‘HTTP_CLIENT_IP‘))
            {
                $realip = getenv(‘HTTP_CLIENT_IP‘);
            }
            else
            {
                $realip = getenv(‘REMOTE_ADDR‘);
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : ‘0.0.0.0‘;
        return $realip;
    }

 /**
     * 鳳?督昢け腔ip
     *
     *
     * @return string
     * */
    function real_ip_server ()
    {
        static $serverip = NULL;
        if ($serverip !== NULL)
        {
            return $serverip;
        }
        if (isset($_SERVER))
        {
            if (isset($_SERVER[‘SERVER_ADDR‘]))
            {
                $serverip = $_SERVER[‘SERVER_ADDR‘];
            }
            else
            {
                $serverip = ‘0.0.0.0‘;
            }
        }
        else
        {
            $serverip = getenv(‘SERVER_ADDR‘);
        }
        return $serverip;
    }

public static function is_url($str)
    {
        return preg_match("/((http[s]?|ftp):\/\/)?[^\/\.]+?\..+\w$/i", $str);
    }

    /**
     * 旯爺痐
     *
     * @param string $id
     * @return boolean
     */
    public static function is_idcard($id)
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if (!preg_match($regx, $id))
        {
            return FALSE;
        }
        if (15 == strlen($id)) //潰脤15弇
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
            @preg_match($regx, $id, $arr_split);
            //潰脤汜゜゜ヽ岆瘁淏?
            $dtm_birth = "19" . $arr_split[2] . ‘/‘ . $arr_split[3] . ‘/‘ . $arr_split[4];
            if (!strtotime($dtm_birth))
            {
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
        else //潰脤18弇
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . ‘/‘ . $arr_split[3] . ‘/‘ . $arr_split[4];
            if (!strtotime($dtm_birth)) //潰脤汜゜゜ヽ岆瘁淏?
            {
                return FALSE;
            }
            else
            {
                //潰桄18弇旯爺痐腔苺桄鎢岆瘁淏?﹝
                //苺桄弇偌桽ISO 7064:1983.MOD 11-2腔寞隅汜傖ㄛX褫眕'峈岆杅趼10﹝
                $arr_int = array(
                    7,
                    9,
                    10,
                    5,
                    8,
                    4,
                    2,
                    1,
                    6,
                    3,
                    7,
                    9,
                    10,
                    5,
                    8,
                    4,
                    2
                );
                $arr_ch = array(
                    ‘1‘,
                    ‘0‘,
                    ‘X‘,
                    ‘9‘,
                    ‘8‘,
                    ‘7‘,
                    ‘6‘,
                    ‘5‘,
                    ‘4‘,
                    ‘3‘,
                    ‘2‘
                );
                $sign = 0;
                for ($i = 0; $i < 17; $i++)
                {
                    $b = (int)$id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id, 17, 1))
                {
                    return FALSE;
                }
                else
                {
                    return TRUE;
                }
            }
        }
    }

    /**
     * 桄痐怀?腔蚘璃華硊岆瘁磁楊
     *
     * @param string $email 剒猁桄痐腔蚘璃華硊
     *
     * @return bool
     */
    public static function is_email($user_email)
    {
        $chars = "/^([a-z0-9+_]|\\-|\\.)[email protected](([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
        if (strpos($user_email, ‘@‘) !== false && strpos($user_email, ‘.‘) !== false)
        {
            if (preg_match($chars, $user_email))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
//快速排序
function quick_sort($array){
  if (count($array) <= 1) return $array;
  $key = $array[0];
  $left_arr = array();
  $right_arr = array();
  for ($i=1; $i<count($array); $i++){
    if ($array[$i] <= $key)
      $left_arr[] = $array[$i];
    else
      $right_arr[] = $array[$i];
  }
  $left_arr = quick_sort($left_arr);
  $right_arr = quick_sort($right_arr);
  return array_merge($left_arr, array($key), $right_arr);
}

//冒泡排序法
function bubble_sort($array){
    $count = count($array);
    if ($count <= 0) return false;
    for($i=0; $i<$count; $i++){
        for($j=$count-1; $j>$i; $j--){
            if ($array[$j] < $array[$j-1]){
                $tmp = $array[$j];
                $array[$j] = $array[$j-1];
                $array[$j-1] = $tmp;
             }
         }
     }
    return $array;
} 

/**
     * 潰脤岆瘁峈珨跺磁楊腔奀潔跡宒
     *
     * @param   string  $time
     * @return  void
     */
    public static function is_time($time)
    {
        $pattern = ‘/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/‘;
        return preg_match($pattern, $time);
    }
/PHP倒计时
//php的时间是以秒算。js的时间以毫秒算
date_default_timezone_set(‘PRC‘);
//date_default_timezone_set("Asia/Hong_Kong");//地区
//配置每天的活动时间段
$starttimestr = "08:00:00";
$endtimestr = "22:00:00";
$starttime = strtotime($starttimestr);
$endtime = strtotime($endtimestr);
$nowtime = time();
if ($nowtime<$starttime){
die("活动还没开始,活动时间是:{$starttimestr}至{$endtimestr}");
}
$lefttime = $endtime-$nowtime; //实际剩下的时间(秒)
/*
<!--<script language="JavaScript">
<!-- //
var runtimes = 0;
function GetRTime(){
var nMS = <?=$lefttime?>*1000-runtimes*1000;
var nH=Math.floor(nMS/(1000*60*60))%24;
var nM=Math.floor(nMS/(1000*60)) % 60;
var nS=Math.floor(nMS/1000) % 60;
document.getElementById("RemainH").innerHTML=nH;
document.getElementById("RemainM").innerHTML=nM;
document.getElementById("RemainS").innerHTML=nS;
if(nMS>5*59*1000&&nMS<=5*60*1000)
{
alert("还有最后五分钟!");
}
runtimes++;
setTimeout("GetRTime()",1000);
}
window.onload=GetRTime;
// -->
</script>
<!--/*<h4><strong id="RemainH">XX</strong>:<strong id="RemainM">XX</strong>:<strong id="RemainS">XX</strong></h4>*/


//判断文件是否存在,远程
function es_file_exists($file){

        if(preg_match(‘/^http:\/\//‘,trim($file))){
            $file = str_replace(‘ ‘,‘%20‘,$file);
            $file = trim($file);

            $parseurl=parse_url($file);

            if( ! isset($_ENV[‘base_url_flag‘][$parseurl[‘host‘]])){//先判斷一下域名是否能訪問的了
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $parseurl[‘host‘]);
                curl_setopt($ch, CURLOPT_HEADER, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
                $contents = curl_exec($ch);
                $_ENV[‘base_url_flag‘][$parseurl[‘host‘]] = (!$contents || preg_match("/404/", $contents)) ? false : true;

            }

            if($_ENV[‘base_url_flag‘][$parseurl[‘host‘]] === false){
                return false;
            }

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $file);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
            $contents = curl_exec($ch);
            if ($contents){
                $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($statusCode == 200) {
                    return true;
                }
            }
            return false;
        }
        return file_exists(trim($file));//本地的
    }


class Autoloader {
    protected static $classPaths = array();
    protected static $classFileSuffix = ‘.class.php‘;
    protected static $cacheFilePath = null;
    protected static $cachedPaths = null;
    protected static $excludeFolderNames = ‘/^CVS|\..*$/‘; // CVS directories and directories starting with a dot (.).
    protected static $hasSaver = false;

    /**
     * Sets the paths to search in when looking for a class.
     *
     * @param array $paths
     * @return void
     **/
    public static function setClassPaths($paths) {
        self::$classPaths = $paths;
    }

    /**
     * Adds a path to search in when looking for a class.
     *
     * @param string $path
     * @return void
     **/
    public static function addClassPath($path) {
        self::$classPaths[] = $path;
    }

    /**
     * Set the full file path to the cache file to use.
     *
     * Example:
     *
     *     <code>
     *     Autoloader::setCacheFilePath(‘/tmp/class_path_cache.txt‘);
     *     </code>
     *
     * @param string $path
     * @return void
     **/
    public static function setCacheFilePath($path) {
        self::$cacheFilePath = $path;
    }

    /**
     * Sets the suffix to append to a class name in order to get a file name
     * to look for
     *
     * @param string $suffix - $className . $suffix = filename.
     * @return void
     **/
    public static function setClassFileSuffix($suffix) {
        self::$classFileSuffix = $suffix;
    }

    /**
     * When searching the {@link $classPaths} recursively for a matching class
     * file, folder names matching $regex will not be searched.
     *
     * Example:
     *
     *     <code>
     *     Autoloader::excludeFolderNamesMatchingRegex(‘/^CVS|\..*$/‘);
     *     </code>
     *
     * @param string $regex
     * @return void
     **/
    public static function excludeFolderNamesMatchingRegex($regex) {
        self::$excludeFolderNames = $regex;
    }

    /**
     * Returns true if the class file was found and included, false if not.
     *
     * @return boolean
     **/
    public static function loadClass($className) {

        $filePath = self::getCachedPath($className);
        if ($filePath && file_exists($filePath)) {
            // Cached location is correct
            include($filePath);
            return true;
        } else {
            // Scan for file
            foreach (self::$classPaths as $path) {
                if ($filePath = self::searchForClassFile($className, $path)) {
                    self::$cachedPaths[$className] = $filePath;
                    if (!self::$hasSaver) {
                        register_shutdown_function(array(‘Autoloader‘, ‘saveCachedPaths‘));
                        self::$hasSaver = true;
                    }
                    include($filePath);
                    return true;
                }
            }

        }
        return false;
    }

    protected static function getCachedPath($className) {
        self::loadCachedPaths();
        if (isset(self::$cachedPaths[$className])) {
            return self::$cachedPaths[$className];
        } else {
            return false;
        }
    }

    protected static function loadCachedPaths() {
        if (is_null(self::$cachedPaths)) {
            if (self::$cacheFilePath && is_file(self::$cacheFilePath)) {
                self::$cachedPaths = unserialize(file_get_contents(self::$cacheFilePath));
            }
        }
    }

    /**
     * Write cached paths to disk.
     *
     * @return void
     **/
    public static function saveCachedPaths() {
        if (!file_exists(self::$cacheFilePath) || is_writable(self::$cacheFilePath)) {
            $fileContents = serialize(self::$cachedPaths);
            $bytes = file_put_contents(self::$cacheFilePath, $fileContents);
            if ($bytes === false) {
                trigger_error(‘Autoloader could not write the cache file: ‘ . self::$cacheFilePath, E_USER_ERROR);
            }
        } else {
            trigger_error(‘Autoload cache file not writable: ‘ . self::$cacheFilePath, E_USER_ERROR);
        }
    }

    protected static function searchForClassFile($className, $directory) {
        if (is_dir($directory) && is_readable($directory)) {
            $d = dir($directory);
            while ($f = $d->read()) {
                $subPath = $directory . $f;
                if (is_dir($subPath)) {
                    // Found a subdirectory
                    if (!preg_match(self::$excludeFolderNames, $f)) {
                        if ($filePath = self::searchForClassFile($className, $subPath . ‘/‘)) {
                            return $filePath;
                        }
                    }
                } else {
                    // Found a file
                    if ($f == $className . self::$classFileSuffix) {
                        return $subPath;
                    }
                }
            }
        }
        return false;
    }

}


php一些常用函数

时间: 2024-10-12 23:54:45

php一些常用函数的相关文章

Data Frame的常用函数

1.DataFrame的常用函数: (1)np.abs(frame) 绝对值, (2)apply function, lambda f= lambda x: x.max()-x.min(),frame.apply(f); frame.apply(f,axis = 1) f(x), def f(x): return Series([x.min(),x.max()], index=['min','max']),frame.apply(f)(3) applymap format f= lambda x

Oracle SQL语言之常用函数_超越OCP精通Oracle视频教程培训30

Oracle SQL语言之常用函数_超越OCP精通Oracle视频教程培训30 本课程介绍: Oracle视频教程,风哥本套oracle教程培训是<<Oracle数据库SQL语言实战培训教程>>的第5/5套:Oracle SQL语言之常用函数.主要学习Oracle数据库SQL聚合函数,分组函数,字符函数,转换函数,日期字符数字转换,日期函数,集合函数,分析函数等. Oracle SQL语言之常用函数,课程内容详细如下: 聚合函数-数据统计 分组函数-使用group by与havin

MySQL学习笔记(三)——计算字段及常用函数

拼接字段-Concat()函数        将值连接在一起构成单个值.注意:大多数DBMS使用+或者||来实现拼接,mysql则使用Concat()函数来实现. 去空格函数-Trim函数        Trim去掉串左右两边的空格,RTrim去掉串右边的空格,LTrim去掉左边的空格. 使用别名-AS        我们希望查出的新列能有个简介明了的列名,可以用AS来赋予别名. 执行算术运算(+,-,*,/) 大多数sql实现支持以下类型的函数: 1.用于处理文本串(如删除或填充值,转换值为大

162个php常用函数基础用法(个人整理)

PHP常用函数总结 数学函数 1.abs(): 求绝对值 $abs = abs(-4.2); //4.2 数字绝对值数字 2.ceil(): 进一法取整 echo ceil(9.999); // 10 浮点数进一取整 3.floor(): 舍去法取整 echo floor(9.999); // 9 浮点数直接舍去小数部分 4.fmod(): 浮点数取余 ? 1 2 3 4 $x = 5.7; $y = 1.3; // 两个浮点数,x>y 浮点余数 $r = fmod($x, $y); // $r

sql server常用函数、常用语句

一.常用函数 1.字符串函数 : charindex(':','abc:123')    --寻找一个字符在一段字符串中起始的位置 len('zhangsan')   --获取一段字符串的长度 left('Ly,君子之耀',2) --从一段字符串左边返回指定长度的字符 right(char_expr,int_expr)  --返回字符串右边int_expr个字符 substring(expression,start,length) --截取字符串 datalength(Char_expr)  -

常用函数

字符串函数: concat ('xiao','qun'); =====>xiaoqun insert('woshixiaozou',10,3,'qun'); =====> woshixiaoqun select lower('XIAOQUN'),upper('xiaoqun'); =====> xiaoqun XIAOQUN select left('xiaoqunwoshi',7),right('xiaoqunwoshi',5); =====>xiaoqun woshi sele

js常用函数和常用技巧

学习和工作的过程中总结的干货,包括常用函数.常用js技巧.常用正则表达式.git笔记等.为刚接触前端的童鞋们提供一个简单的查询的途径,也以此来缅怀我的前端学习之路. PS:此文档,我会持续更新. Ajax请求 jquery ajax函数 我自己封装了一个ajax的函数,代码如下: var Ajax = function(url, type success, error) { $.ajax({ url: url, type: type, dataType: 'json', timeout: 100

dplyr 数据操作 常用函数(4)

接下来我们继续了解一些dplyr中的常用函数. 1.ranking 以下各个函数可以实现对数据进行不同的排序 row_number(x) ntile(x, n) min_rank(x) dense_rank(x) percent_rank(x) cume_dist(x) 具体的看些例子. x <- c(5, 1, 3, 2, 2, NA) x row_number(x) row_number是对数据大小进行编号排序,遇到重复值,排序继续加1,缺失值不计入 min_rank(x) min_rank

【COCOS CREATOR 系列教程之二】脚本开发篇&事件监听、常用函数等示例整合

[Cocos Creator ](千人群):  432818031 上一篇,介绍了Himi在使用过cc所有组件后的一篇总结,没有具体介绍每个组件的原因在于官方文档很齐全,而且也有视频的介绍. 所以希望童鞋们可以把我这两篇博文当成对组件.脚本两部分开发的整理与总结. 后续的文章,Himi应该主要更新一些官方还未补充或者还没有的教程.避免无用功. 下面直接放出代码,因为不是很难理解.所以不再一一赘述,都是常用的函数.事件监听.动作回调.定时器等开发过程中必接触的. 大致内容如下: cc 属性介绍 获

phpcms V9 常用函数 及 代码整理

常用函数 及 常用代码 总结如下 1 <?php 2 //转换字符串或者数组的编码 3 str_charset($in_charset, $out_charset, $str_or_arr) 4 5 //获取菜单 6 menu($parentid, $code = '') 7 8 //判断当前浏览器是否为IE 9 is_ie() 10 11 //检查日期的合法性 12 is_date($ymd, $sep='-') 13 14 // 检查邮箱的合法性 15 is_email($email) 16