php类的注册与自动加载__autoload

 更新时间:2016年11月25日 17:30  点击:1684
__autoload() 是PHP执行环境中约定的一个函数而非某个类的方法,如果一个类在使用之前没有加载到当前文件,会自动调用 __autoload() 函数来加载该类,通常这些类的加载规则都是约定的,比如这些类包含在以类名命名的文件内,该方法可以实现类的按需加载,避免脚本执行前加载不必要的类从而降低资源占用、提交性能。

注意:__autoload() 内的错误不能被 try-catch 捕获。

 代码如下 复制代码

function __autoload($class_name){

     require_once(PATH.'/calsses/'.$class_name.'.php');

}

$obj1 = new mycalss1();

注册 __autoload() 自动调用的函数:

spl 代码库在 PHP5.0 之后默认自动启用

spl_autoload_register([callback]); //不将具体实现的加载代码写在 __autoload() 内,可使用该函数注册回调函数。

如果使用类的方法作为回调函数需要传入一个数组:

 代码如下 复制代码

spl_autoload_register(array('class_name'|$obj,'method_name'));

例如:

spl_autoload_register(array($this,'autoloadClass'));

spl_autoload_register(array('YiiBase','autoload'));// YII 框架的自动加载类的实现, YiiBase 类实现了一个autoload 方法。  spl_autoload_register() 可以注册多个加载函数,成功加载类文件之前将逐个尝试所有注册的加载函数。这在不同的类使用不同逻辑来导入类文件的时候很有用。

spl_autoload_unregister(); //取消某个注册的加载函数,参数与 spl_autoload_register() 相同.

spl_autoload_functions();// 以数组形式返回所有注册的 __autoload() 函数

 

spl_autoload(class_name[,file_extentions]); // __autoload() 函数的默认实现。 spl_autoload_register() 被调用时如果没有传入 函数名,则默认使用该函数,该函数的执行规则是: 类名转为小写作为文件名,传入的 file_extentions(多个扩展名以逗号隔开,默认为 .inc 和 .php)为扩展名,根据得到的文件名尝试在 php.ini 内设置的 include paths 中搜索。

 spl_autoload_call(class_name);//手动调用所有注册的 __autoload() 函数来主动加载类文件

spl_autoload_extentions([file_extentions]); //注册或返回 spl_autoload() 中可以使用的文件扩展名,扩展名可以是 .a.b 这样的形式,例如:

 

 代码如下 复制代码

spl_autoload_extentions(".class.php");

spl_autoload_register(); //使用spl_autoload() 来尝试自动加载类文件

//这样 spl_autoload('myclassName'); 会尝试加载 文件 "myclassName.class.php" .

实例

1、将需要注册的类放在一个数组中

 代码如下 复制代码


<?php
final class Utils {

    private function __construct() {

    }

    public static function getClasses($pre_path = '/') {
        $classes = array(
                'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
                'User' => $pre_path.'Model/User.php',
                'Dao' => $pre_path.'Dao/Dao.php',
                'UserDao' => $pre_path.'Dao/UserDao.php',
                'UserMapper' => $pre_path.'Mapping/UserMapper.php',
        );
        return $classes;
    }
}
?>

2、注册数组

注意:步骤1中的类的路径都是相对于init.php而言的,不是相对于Utils而言的,这是因为我们通过init.php里的自动加载函数spl_autoload_register来require类的

 代码如下 复制代码


<?php
require_once '/Utils/Utils.php';
final class Init {
   
    /**
     * System config.
     */
    public function init() {
        // error reporting - all errors for development (ensure you have
        // display_errors = On in your php.ini file)
        error_reporting ( E_ALL | E_STRICT );
        mb_internal_encoding ( 'UTF-8' );
        //registe classes
        spl_autoload_register ( array ($this,'loadClass' ) );
    }
   
    /**
     * Class loader.
     */
    public function loadClass($name) {
        $classes = Utils::getClasses ();
        if (! array_key_exists ( $name, $classes )) {
            die ( 'Class "' . $name . '" not found.' );
        }
        require_once $classes [$name];
    }
}
$init = new Init ();
$init->init ();
?>

3、本例中在使用处test.php里require init.php

 

 代码如下 复制代码

<?php
require_once 'Init.php';

$dao = new UserDao();
$result = $dao->findByName('zcl');
?>

很早的时候,用php生成execl都是件麻烦的事,我一般都会用csv来替代,现在这类工具就很多了,并且比较成熟了。不光有excel的,word,pdf。

1,php excelreader操作excel的php类,生成,读取excel等。功能很强大。

下载地址:http://sourceforge.net/projects/phpexcelreader/

解压后,里面有很多例子,调用方法简单。

例1

 代码如下 复制代码

<?php
/**
 *
 * @copyright 2007-2012 Xiaoqiang.
 * @author Xiaoqiang.Wu <jamblues@gmail.com>
 * @version 1.01
 */
 
error_reporting(E_ALL);
 
date_default_timezone_set('Asia/ShangHai');
 
/** PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
 
 
// Check prerequisites
if (!file_exists("31excel5.xls")) {
 exit("not found 31excel5.xls.n");
}
 
$reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
$PHPExcel = $reader->load("31excel5.xls"); // 载入excel文件
$sheet = $PHPExcel->getSheet(0); // 读取第一??工作表
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumm = $sheet->getHighestColumn(); // 取得总列数
$highestColumm= PHPExcel_Cell::columnIndexFromString($colsNum); //字母列转换为数字列 如:AA变为27
 
/** 循环读取每个单元格的数据 */
for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
    for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
        $columnName = PHPExcel_Cell::stringFromColumnIndex($column);
        echo $columnName.$row.":".$sheet->getCellByColumnAndRow($column, $row)->getValue()."<br />";
    }
}
 
?>

例2

 代码如下 复制代码

<?php
/**
 *
 * @copyright 2007-2012 Xiaoqiang.
 * @author Xiaoqiang.Wu <jamblues@gmail.com>
 * @version 1.01
 */
 
error_reporting(E_ALL);
 
date_default_timezone_set('Asia/ShangHai');
 
/** PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
 
 
// Check prerequisites
if (!file_exists("31excel5.xls")) {
 exit("not found 31excel5.xls.n");
}
 
$reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
$PHPExcel = $reader->load("31excel5.xls"); // 载入excel文件
$sheet = $PHPExcel->getSheet(0); // 读取第一??工作表
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumm = $sheet->getHighestColumn(); // 取得总列数
 
/** 循环读取每个单元格的数据 */
for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
        $dataset[] = $sheet->getCell($column.$row)->getValue();
        echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
    }
}
 
?>

2,phpdocx操作word的php类

PHPDocx是一个用于生成完全动态的、完全兼容的Word文档的PHP类库。

你可能需要直接从任何数据集合或者表格文件来生成报表。这些报表也许会包括图标、图片、表格、开头、结束等等数据。

PHPDocx能够使用一些预定义的模板文件来生成Word文档,这大大简化了工作量。使用很少的一些代码,你能够将PHPDocx集成到你的WEB站点或网络应用,这样能够为你的用户或雇员提供一个很有价值的服务。

 代码如下 复制代码

Basic example
// Include the PHPWord.php, all other classes were loaded by an autoloader
require_once 'PHPWord.php';

// Create a new PHPWord Object
$PHPWord = new PHPWord();

// Every element you want to append to the word document is placed in a section. So you need a section:
$section = $PHPWord->createSection();

// After creating a section, you can append elements:
$section->addText('Hello world!');

// You can directly style your text by giving the addText function an array:
$section->addText('Hello world! I am formatted.', array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));

// If you often need the same style again you can create a user defined style to the word document
// and give the addText function the name of the style:
$PHPWord->addFontStyle('myOwnStyle', array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232'));
$section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');

// You can also putthe appended element to local object an call functions like this:
$myTextElement = $section->addText('Hello World!');
$myTextElement->setBold();
$myTextElement->setName('Verdana');
$myTextElement->setSize(22);

// At least write the document to webspace:
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('helloWorld.docx');

下载地址:http://www.phpdocx.com/

在线演示地址:http://www.phpdocx.com/demo/sample-word-report

3,tcpdf操作pdf的php类

下载地址:http://sourceforge.net/projects/html2fpdf/?source=recommended

在线演示地址:http://www.tcpdf.org/examples.php

下载后,基本上都是有例子的,下载后的东西比较大,这是因为,里面有很多例子,供例子用的pdf,word文件这类,也有很多字体文件。要用的类文件其实并不大的。记录一下用的时候,就不用到处找了。哈哈。

TCPDF自带的65个examples之后,就能完全掌握它的使用方法了。

大体可以分为如下5个步骤:

1.      require_once导入tcpdf.php文件和config/lang/目录的相应语系

2.      实例化TCPDF

3.      设置PDF文档的格式,包括文档信息、页眉、页尾、字体、外间距、图片边框、分页等

4.      导入PDF文档的内容,可以是单行或多行简单字符串,也可以HTML格式的字符串等

5.      输出PDF文档

一个网友写的地市联动的php分类程序,大家可参考参考。

写一个函数,将数据

 代码如下 复制代码
$array = array(
    0=>array("","河北"),
    1=>array("","北京"),
    2=>array(0,"保定"),
    3=>array(1,"海淀"),
    4=>array(3,"中关村"),
    5=>array(2,"涿州")
);


处理后返回如下:
河北
-保定
--涿州
北京
-海淀
--中关村

 

 代码如下 复制代码
function typeArray($array){
   $con = null;
   foreach ($array as $k=>$v){
        $na[$k] = is_numeric($v[0]) ? $na[$v[0]].$k."|" : $k."|";
    }
   asort($na);
   foreach ($na as $k=>$v){
     $s = substr_count($v,"|");
      $con .= str_repeat("-",($s-1)).$array[$k][1]."n";
    }
    return $con;
}
常用的php各种验证正则表达式程序
 代码如下 复制代码
class validator
 
{
 
    /**
 
     * Checks that a field is exactly the right length.
 
     * Constructer PHP4     
 
     */
 
    function validator()
 
    {
 
    }
 
    /**
 
     * check a number optional -,+,. values
 
     * @param   string        
 
     * @return  boolean
 
     */
 
    function is_numeric($val)
 
    {
 
        return (bool)preg_match('/^[-+]?[0-9]*.?[0-9]+$/', $val);
 
    }
 
    /**
 
     * valid email     
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_email($val)
 
    {
 
        return (bool)(preg_match("/^([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6}$/i",
 
            $val));
 
    }
 
    /**
 
     * Valid URL or web address
 
     * @param   string      
 
     * @return  boolean
 
     */
 
    function is_url($val)
 
    {
 
        return (bool)preg_match("^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$",
 
            $val);
 
    }
 
    /**
 
     * Valid IP address
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_ipaddress($val)
 
    {
 
        return (bool)preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",
 
            $val);
 
    }
 
    /**
 
     * Matches only alpha letters
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_alpha($val)
 
    {
 
        return (bool)preg_match("/^([a-zA-Z])+$/i", $val);
 
    }
 
    /**
 
     * Matches alpha and numbers only
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_alphanumeric($val)
 
    {
 
        return (bool)preg_match("/^([a-zA-Z0-9])+$/i", $val);
 
    }
 
    /**
 
     * Matches alpha ,numbers,-,_ values
 
     * @param   string  
 
     * @return  boolean
 
     */
 
    function is_alphanumericdash($val)
 
    {
 
        return (bool)preg_match("/^([-a-zA-Z0-9_-])+$/i", $val);
 
    }
 
    /**
 
     * Matches alpha and dashes like -,_
 
     * @param   string  
 
     * @return  boolean
 
     */
 
    function is_alphadash($val)
 
    {
 
        return (bool)preg_match("/^([A-Za-z_-])+$/i", $val);
 
    }
 
    /**
 
     *Matches exactly number
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_integer($val)
 
    {
 
        return is_int($val);
 
    }
 
    /**
 
     * Valid Credit Card
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_creditcard($val)
 
    {
 
        return (bool)preg_match("/^((4d{3})|(5[1-5]d{2})|(6011)|(7d{3}))-?d{4}-?d{4}-?d{4}|3[4,7]d{13}$/",
 
            $val);
 
    }
 
    /**
 
     * check given string length is between given range 
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_rangelength($val, $min = '', $max = '')
 
    {
 
        return (strlen($val) >= $min and strlen($val) <= $max);
 
    }
 
    /**
 
     *Check the string length has minimum length
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_minlength($val, $min)
 
    {
 
        return (strlen($val) >= (int)$min);
 
    }
 
    /**
 
     * check string length exceeds maximum length     
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_maxlength($val, $max)
 
    {
 
        return (strlen($val) <= (int)$max);
 
    }
 
    /**
 
     * check given number exceeds max values   
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_maxvalue($number,$max)
 
    {
 
         return ($number >$max);
 
    }
 
    /**
 
     * check given number below value   
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_minvalue($number)
 
    {
 
        return ($number < $max);
 
    }
 
    /**
 
     * check given number between given values
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_rangevalue($number,$min,$max)
 
    {
 
        return ($number >$min and $number<$max);
 
    }
 
    /**
 
     * check for exactly length of string
 
     * @param   string  
 
     * @return  boolean
 
     */
 
    function is_length($val, $length)
 
    {
 
        return (strlen($val) == (int)$length);
 
    }
 
    /**
 
     * check decimal with . is optional and after decimal places up to 6th precision
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_decimal($val)
 
    {
 
        return (bool)preg_match("/^d+(.d{1,6})?$/'", $val);
 
    }
 
    /**
 
     * Valid hexadecimal color ,that may have #,
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_hexcolor($color)
 
    {
 
        return (bool)preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/i', $color);
 
    }
 
    /**
 
     * Matches  againest given regular expression ,including delimeters
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_regex($val, $expression)
 
    {
 
        return (bool)preg_match($expression, (string )$val);
 
    }
 
    /**
 
     * compares two any kind of values ,stictly
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_matches($val, $value)
 
    {
 
        return ($val === $value);
 
    }
 
    /**
 
     * check if field empty string ,orject,array
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_empty($val)
 
    {
 
        return in_array($val, array(null, false, '', array()), true);
 
    }
 
    /**
 
     * Check if given string matches any format date
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_date($val)
 
    {
 
        return (strtotime($val) !== false);
 
    }
 
    /**
 
     * check given string againest given array values
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_enum($val, $arr)
 
    {
 
        return in_array($val, $arr);
 
    }
 
    /**
 
     * Checks that a field matches a v2 md5 string
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_md5($val)
 
    {
 
        return (bool)preg_match("/[0-9a-f]{32}/i", $val);
 
    }
 
    /**
 
     * Matches base64 enoding string
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_base64($val)
 
    {
 
        return (bool)!preg_match('/[^a-zA-Z0-9/+=]/', $val);
 
    }
 
    /**
 
     * check if array has unique elements,it must have  minimum one element
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_unique($arr)
 
    {
 
        $arr = (array )$arr;
 
        $count1 = count($arr);
 
        $count2 = count(array_unique($arr));
 
        return (count1 != 0 and (count1 == $count2));
 
    }
 
    /**
 
     * Check is rgb color value
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_rgb($val)
 
    {
 
        return (bool)preg_match("/^(rgb(s*b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])bs*,s*b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])bs*,s*b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])bs*))|(rgb(s*(d?d%|100%)+s*,s*(d?d%|100%)+s*,s*(d?d%|100%)+s*))$/",
 
            $val);
 
    }
 
    /**
 
     * is given field is boolean value or not
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_boolean($val)
 
    {
 
        $booleans = array(1, 0, '1', '0', true, false, true, false);
 
        $literals = array('true', 'false', 'yes', 'no');
 
        foreach ($booleans as $bool) {
 
            if ($val === $bool)
 
                return true;
 
        }
 
        return in_array(strtolower($val), $literals);
 
    } 
 
    /**
 
     * A token that don't have any white space
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_token($val)
 
    {
 
        return (bool)!preg_match('/s/', $val);
 
    }
 
    /**
 
     * Checks that a field is exactly the right length.
 
     * @param   string   value
 
     * @link  http://php.net/checkdnsrr  not added to Windows until PHP 5.3.0
 
     * @return  boolean
 
     */
 
    function is_emaildomain($email)
 
    {
 
        return (bool)checkdnsrr(preg_replace('/^[^@]++@/', '', $email), 'MX');
 
    }
 
    /**
 
     * Matches a phone number that length optional numbers 7,10,11
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_phone($number, $lengths = null)
 
    {
 
        if (!is_array($lengths)) {
 
            $lengths = array(7, 10, 11);
 
        }
 
        $number = preg_replace('/D+/', '', $number);
 
        return in_array(strlen($number), $lengths);
 
    }
 
    /**
 
     * check given sting is UTF8 
 
     * @param   string  
 
     * @return  boolean
 
     */
 
    function is_utf8($val)
 
    {
 
        return preg_match('%(?:
 
        [xC2-xDF][x80-xBF]        
 
        |xE0[xA0-xBF][x80-xBF]               
 
        |[xE1-xECxEExEF][x80-xBF]{2}     
 
        |xED[x80-x9F][x80-xBF]               
 
        |xF0[x90-xBF][x80-xBF]{2}   
 
        |[xF1-xF3][x80-xBF]{3}                  
 
        |xF4[x80-x8F][x80-xBF]{2}    
 
        )+%xs', $val);
 
    }
 
    /**
 
     * Given sting is lower cased
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_lower($val)
 
    {
 
        return (bool)preg_match("/^[a-z]+$/", $val);
 
    }
 
    /**
 
     * Given string is upper cased?
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_upper($val)
 
    {
 
        return (bool)preg_match("/^[A-Z]+$/", $val);
 
    }
 
    /**
 
     * Checks that given value matches following country pin codes.     
 
     * at = austria
 
     * au = australia
 
     * ca = canada
 
     * de = german
 
     * ee = estonia
 
     * nl = netherlands
 
     * it = italy
 
     * pt = portugal
 
     * se = sweden
 
     * uk = united kingdom
 
     * us = united states
 
     * @param String   
 
     * @param String
 
     * @return  boolean
 
     */
 
    function is_pincode($val, $country = 'us')
 
    {
 
        $patterns = array('at' => '^[0-9]{4,4}$', 'au' => '^[2-9][0-9]{2,3}$', 'ca' =>
 
            '^[a-zA-Z].[0-9].[a-zA-Z].s[0-9].[a-zA-Z].[0-9].', 'de' => '^[0-9]{5,5}$', 'ee' =>
 
            '^[0-9]{5,5}$', 'nl' => '^[0-9]{4,4}s[a-zA-Z]{2,2}$', 'it' => '^[0-9]{5,5}$',
 
            'pt' => '^[0-9]{4,4}-[0-9]{3,3}$', 'se' => '^[0-9]{3,3}s[0-9]{2,2}$', 'uk' =>
 
            '^([A-Z]{1,2}[0-9]{1}[0-9A-Z]{0,1}) ?([0-9]{1}[A-Z]{1,2})$', 'us' =>
 
            '^[0-9]{5,5}[-]{0,1}[0-9]{4,4}$');
 
        if (!array_key_exists($country, $patterns))
 
            return false;
 
        return (bool)preg_match("/" . $patterns[$country] . "/", $val);
 
    }
 
    /**
 
     * Check given url really exists?
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_urlexists($link)
 
    {
 
        if (!$this->is_url($link))
 
            return false;
 
        return (bool)@fsockopen($link, 80, $errno, $errstr, 30);
 
    }
 
    /**
 
     * Check given sting has script tags
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_jssafe($val)
 
    {
 
        return (bool)(!preg_match("/<script[^>]*>[srn]*(<!--)?|(-->)?[srn]*</script>/",
 
            $val));
 
    }
 
    /**
 
     * given sting has html tags?
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_htmlsafe($val)
 
    {
 
        return (bool)(!preg_match("/<(.*)>.*</$1>/", $val));
 
    }
 
    /**
 
     * check given sring has multilines 
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_multiline($val)
 
    {
 
        return (bool)preg_match("/[nrt]+/", $val);
 
    }
 
    /**
 
     * check given array key element exists?
 
     * @param   string   
 
     * @return  boolean
 
     */
 
    function is_exists($val, $arr)
 
    {
 
        return isset($arr[$val]);
 
    }
 
    /**
 
     * is given string is ascii format?
 
     * @param   string        
 
     * @return  boolean
 
     */
 
    function is_ascii($val)
 
    {
 
        return !preg_match('/[^x00-x7F]/i', $val);
 
    }
 
    /**
 
     * Checks given value again MAC address of the computer
 
     * @param   string   value      
 
     * @return  boolean
 
     */
 
    function is_macaddress($val)
 
    {
 
        return (bool)preg_match('/^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/',
 
            $val);
 
    }
 
    /**
 
     * Checks given value matches us citizen social security number
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_usssn($val)
 
    {
 
        return (bool)preg_match("/^d{3}-d{2}-d{4}$/", $val);
 
    }
 
    /**
 
     * Checks given value matches date de
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_dateDE($date)
 
    {
 
        return (bool)preg_match("/^dd?.dd?.ddd?d?$/", $date);
 
    }
 
    /**
 
     * Checks given value matches us citizen social security number
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_dateISO($date)
 
    {
 
        return (bool)preg_match("/^d{4}[/-]d{1,2}[/-]d{1,2}$/", $date);
 
    }
 
    /**
 
     * Checks given value matches a time zone  
 
     * +00:00 | -05:00 
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_timezone($val)
 
    {
 
        return (bool)preg_match("/^[-+]((0[0-9]|1[0-3]):([03]0|45)|14:00)$/", $val);
 
    }
 
    /**
 
     * Time in 24 hours format with optional seconds
 
     * 12:15 | 10:26:59 | 22:01:15 
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_time24($val)
 
    {
 
        return (bool)preg_match("/^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/",
 
            $val);
 
    }
 
    /**
 
     * Time in 12 hours format with optional seconds
 
     * 08:00AM | 10:00am | 7:00pm
 
     * @param   string         
 
     * @return  boolean
 
     */
 
    function is_time12($val)
 
    {
 
        return (bool)preg_match("/^([1-9]|1[0-2]|0[1-9]){1}(:[0-5][0-9][aApP][mM]){1}$/",
 
            $val);
 
    }
 
}
 
PHP本身自带的有一个readdir的函数,不过只能读取当前的目录,根据这个函数,我写了另外一个函数,用来实现我的需求。函数的原理很简单,主要就是用了一下递归调用。
 代码如下 复制代码

<?php
class listdir{
var $depth;
var $dirname;
var $list;
var $tostring;

function listdir($dir){
$this->dirname=$dir;
$this->depth=0;
$this->tostring=”";
}

//把结果保存进多维数组
function getlist($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
while(false!==($item=$d->read()))
{
if($item!=”.”&&$item!=”..”)
{
$path=$dir.”/”.$item;
if(is_dir($path)){
$this->depth+=1;
$this->getlist($path);
}else{
$this->list[$this->depth][]=$item;
}
}
}
$this->list[$this->depth]['directory']=$dir;
$this->depth-=1;
$d->close();
return $this->list;
}

//字符窜化结果

function tostring($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
$this->tostring.=”<UL>n”;
$this->tostring.=”Directory:”.$dir.”n”;
while(false!==($item=$d->read()))
{
if($item!=”.”&&$item!=”..”)
{
$path=$dir.”/”.$item;
if(is_dir($path)){
$this->depth+=1;
$this->tostring($path);
}else{
$this->tostring.=”<LI>”.$item.”</LI>n”;
}
}
}
$this->depth-=1;
$d->close();
$this->tostring.=”</UL>n”;
return $this->tostring;
}
}
$wapdir=”jquery”;
$d=new listdir($wapdir);
echo $d->tostring();
?>

递归创建多级目录

1.先判断最底层目录div/css/layout是否存在;2.判断div/css/layout的上层目录div/css是否存在,不存在则以div/css作为参数递归进行


下面是程序代码:

 代码如下 复制代码

function mkdirs($dir)
{
if(!is_dir($dir))
{
if(!mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
return true;
}
mkdirs('div/css/layout');


同样的思路,php用rmdir和unlink递归删除多级目录的代码:

function rmdirs($dir)
{
$d = dir($dir);
while (false !== ($child = $d->read())){
if($child != '.' && $child != '..'){
if(is_dir($dir.'/'.$child))
rmdirs($dir.'/'.$child);
else unlink($dir.'/'.$child);
}
}
$d->close();
rmdir($dir);
}

[!--infotagslink--]

相关文章

  • MyBatis-Plus自动填充功能失效导致的原因及解决

    这篇文章主要介绍了MyBatis-Plus自动填充功能失效导致的原因及解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
  • C#实现延时并自动关闭MessageBox的方法

    这篇文章主要介绍了C#实现延时并自动关闭MessageBox的方法,非常实用的功能,需要的朋友可以参考下...2020-06-25
  • SpringMvc自动装箱及GET请求参数原理解析

    这篇文章主要介绍了SpringMvc自动装箱及GET请求参数原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-19
  • 利用Redis如何实现自动补全功能

    这篇文章主要给大家介绍了关于如何利用Redis如何实现自动补全功能的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Redis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-04-17
  • MySQL自动停机的问题处理实战记录

    这篇文章主要给大家介绍了关于MySQL自动停机的问题处理,文中通过示例代码介绍的非常详细,对大家学习或者使用MySQL具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-01
  • Email URL的判断和自动转换函数

    <?php function validateEmail($email) { return eregi("^[_a-z0-9-] (.[_a-z0-9-] )*@[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,3})$", $email); } function validat...2016-11-25
  • Laravel实现autoload方法详解

    本文给大家讲解的是在laravel中是怎么实现autoload的?分析之后才发现,真的是很巧妙,下面就来给大家详细说明下...2017-05-21
  • 类的自动加载

    当你尝试使用一个未定义的类时,PHP会报告一个致命错误. 解决方法就是添加一个类,可以用include包含一个文件. 究竟你知道要用到哪个类. 但是,PHP提供了类的自动加载功...2016-11-25
  • 实例:实现自动清除日期目录shell脚本

    这次文章给大家带来的是一个简单使用的实例:实现自动清除日期目录shell脚本,对脚本感兴趣的下面我们一起来看看那具体的清除日期方法。 实现自动清除日期目录shell...2017-07-06
  • 关闭PayPal预付款,避免自动扣费的教程

    PayPal在国外就是支付宝一样强大了许多的平台都支持PayPal付款了,我信如果购买国外主机肯定会用到PayPal了,今天我们来给各位介绍关闭PayPal预付款,避免自动扣费吧,具体如...2016-10-10
  • PHP微信开发之微信消息自动回复下所遇到的坑

    这篇文章是小编给大家介绍的微信消息自动回复下所遇到的坑的相关内容,在日常项目开发中经常遇到,非常具有参考借鉴价值,感兴趣的小伙伴一起学习吧...2016-05-13
  • 华为Mate9怎么自动删除通知信息 操作设置教程

    华为Mate9如何自动删除通知信息呢?这种操作方法有强迫症的朋友一定要来看一看。 有些华为Mate9用户想要将通知信息设置成自动删除,不过你清楚具体的操作吗?华为Mate9...2017-01-22
  • 深入理解PHP类的自动载入机制

    下面小编就为大家带来一篇深入理解PHP类的自动载入机制。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-02
  • 用PHP脚本自动把纯文本文件转换成Web页面

    最近,我的一个老朋友向我打电话求助。他从事记者的职业有多年了,最近获得了重新出版他的很多早期专栏的权利。他希望把他的作品贴在Web上;但是他的专栏都是以纯文本文件的...2016-11-25
  • 利用PHP代码实现网页自动判断转向

    用户可接受的语言信息,放在$_SERVER['HTTP_ACCEPT_LANGUAGE']里,变量信息是类似这样的 "zh-cn", 假如是多语言列,是类似 "zh-cn,en;q=0.8,ko;q=0.5,zh-tw;q=0.3"   下...2016-11-25
  • PHP5新特性,__autoload

    因为创建PYTHON中国(www.okpython.com)和推广PYTHON,所以一直没时间去研究PHP5的特性,现在终于有时间了。 今天说下__autoload函数的功能: 说明:自动加载类文件...2016-11-25
  • MySql数据库自动递增值问题

    这篇文章主要介绍了MySql数据库自动递增值问题的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下...2016-07-29
  • PHP实现网页自动更新块

      能不能让php为你的网页添加一些每隔一段时间就自动更新的内容,以更好的吸引访客呢?实现这一功能并不需要太高深的编程知识,请看以下例子:   (一)英语谚语   让我们...2016-11-25
  • PHP自动更新新闻DIY

    我们浏览一些网站的时候,往往看到一些新闻是刚刚更新不久的,假如要是人工维护的话,那会是一项非常繁琐的工作。然而,我们可以通过程序来控制实现更新操作,事情就会变得很方...2016-11-25
  • php自动加载__autoload()函数用法

    autoload在php主版本中是自动加载文件的一个方法了我们可以定义许多的文件在目录然后通过autoload加载了,下面来看看autoload函数用法。 在PHP5之后,我们可以通过...2016-11-25