5、魔术常量
PHP提供了获取当前行号(__LINE__)、文件路径(__FILE__)、目录路径(__DIR__)、函数名(__FUNCTION__)、类名(__CLASS__)、方法名(__METHOD__)和命名空间(__NAMESPACE__)等有用的魔术常量。在这篇文章中不作一一介绍,但是我将告诉你一些用例。当包含其他脚本文件时,使用__FILE__常量或者使用PHP5.3新具有的__DIR__常量):
- 以下为引用的内容:
- //thisisrelativetotheloadedscript'spath
- //itmaycauseproblemswhenrunningscriptsfromdifferentdirectories
- require_once('config/database.php');
- //thisisalwaysrelativetothisfile'spath
- //nomatterwhereitwasincludedfrom
- require_once(dirname(__FILE__).'/config/database.php');
使用__LINE__使得调试更为轻松。你可以跟踪到具体行号。
- 以下为引用的内容:
- //somecode
- //...
- my_debug("somedebugmessage",__LINE__);
- /*prints
- Line4:somedebugmessage
- */
- //somemorecode
- //...
- my_debug("anotherdebugmessage",__LINE__);
- /*prints
- Line11:anotherdebugmessage
- */
- functionmy_debug($msg,$line){
- echo"Line$line:$msg
6、生成唯一标识符
某些场景下,可能需要生成一个唯一的字符串。我看到很多人使用md5()函数,即使它并不完全意味着这个目的:
- 以下为引用的内容:
- //generateuniquestring
- echomd5(time().mt_rand(1,1000000));
- ThereisactuallyaPHPfunctionnameduniqid()thatismeanttobeusedforthis.
- //generateuniquestring
- echouniqid();
- /*prints
- 4bd67c947233e
- */
- //generateanotheruniquestring
- echouniqid();
- /*prints
- 4bd67c9472340
- */
你可能会注意到,尽管字符串是唯一的,前几个字符却是类似的,这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面,由于每个新生成的ID会按字母顺序排列,这样排序就变得很简单。为了减少重复的概率,你可以传递一个前缀,或第二个参数来增加熵。
- 以下为引用的内容:
- //withprefix
- echouniqid('foo_');
- /*prints
- foo_4bd67d6cd8b8f
- */
- //withmoreentropy
- echouniqid('',true);
- /*prints
- 4bd67d6cd8b926.12135106
- */
- //both
- echouniqid('bar_',true);
- /*prints
- bar_4bd67da367b650.43684647
- */
这个函数将产生比md5()更短的字符串,能节省一些空间。
7、序列化
你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用serialize()和unserialize()函数。以下为引用的内容:
- //acomplexarray
- $myvar=array(
- 'hello',
- 42,
- array(1,'two'),
- 'apple'
- );
- //converttoastring
- $string=serialize($myvar);
- echo$string;
- /*prints
- a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
- */
- //youcanreproducetheoriginalvariable
- $newvar=unserialize($string);
- print_r($newvar);
- /*prints
- Array
- (
- [0]=>hello
- [1]=>42
- [2]=>Array
- (
- [0]=>1
- [1]=>two
- )
- [3]=>apple
- )
- */
这是原生的PHP序列化方法。然而,由于JSON近年来大受欢迎,PHP5.2中已经加入了对JSON格式的支持。现在你可以使用json_encode()和json_decode()函数,以下为引用的内容:
- //acomplexarray
- $myvar=array(
- ‘hello’,
- 42,
- array(1,’two’),
- ‘apple’
- );
- //converttoastring
- $string=json_encode($myvar);
- echo$string;
- /*prints
- ["hello",42,[1,"two"],”apple”]
- */
- //youcanreproducetheoriginalvariable
- $newvar=json_decode($string);
- print_r($newvar);
- /*prints
- Array
- (
- [0]=>hello
- [1]=>42
- [2]=>Array
- (
- [0]=>1
- [1]=>two
- )
- [3]=>apple
- )
- */
这将更为行之有效,尤其与JavaScript等许多其他语言兼容。然而对于复杂的对象,某些信息可能会丢失。
文章转自PHP之家,
原文地址:http://www.phpzj.org/php_0002.html
PHP之友评论