5、魔术常量
PHP 提供了获取当前行号 (__LINE__)、文件路径 (__FILE__)、目录路径 (__DIR__)、函数名 (__FUNCTION__)、类名 (__CLASS__)、方法名 (__METHOD__) 和命名空间 (__NAMESPACE__) 等有用的魔术常量。在这篇文章中不作一一介绍,但是我将告诉你一些用例。当包含其他脚本文件时,使用 __FILE__ 常量(或者使用 PHP5.3 新具有的 __DIR__ 常量):
以下为引用的内容:
// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
require_once('config/database.php');
// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . '/config/database.php');
使用 __LINE__ 使得调试更为轻松。你可以跟踪到具体行号。
以下为引用的内容:
// some code
// ...
my_debug("some debug message", __LINE__);
/* prints
Line 4: some debug message
*/
// some more code
// ...
my_debug("another debug message", __LINE__);
/* prints
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo "Line $line: $msg
6、生成唯一标识符
某些场景下,可能需要生成一个唯一的字符串。我看到很多人使用 md5() 函数,即使它并不完全意味着这个目的:
以下为引用的内容:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
There is actually a PHP function named uniqid() that is meant to be used for this.
// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/
你可能会注意到,尽管字符串是唯一的,前几个字符却是类似的,这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面,由于每个新生成的 ID 会按字母顺序排列,这样排序就变得很简单。为了减少重复的概率,你可以传递一个前缀,或第二个参数来增加熵:
以下为引用的内容:
// with prefix
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f
*/
// with more entropy
echo uniqid('',true);
/* prints
4bd67d6cd8b926.12135106
*/
// both
echo uniqid('bar_',true);
/* prints
bar_4bd67da367b650.43684647
*/
这个函数将产生比 md5() 更短的字符串,能节省一些空间。