php学习

原文:http://www.viphper.com/?p=541
一、传递任意数量的函数参数

咱们在.NET或者JAVA编程中,通常函数参数个数都是固定的,可是PHP容许你使用任意个数的参数。下面这个示例向你展现了PHP函数的默认参数:php

// 两个默认参数的函数算法

function foo($arg1 = ”, $arg2 = ”) {数据库

echo “arg1: $arg1\n”;编程

echo “arg2: $arg2\n”;json

}windows

foo(‘hello’,’world’);api

/* 输出:数组

arg1: helloapp

arg2: world函数

*/

foo();

/* 输出:

arg1:

arg2:

*/

下面这个示例是PHP的不定参数用法,其使用到了 func_get_args()方法:

// 是的,形参列表为空

function foo() {

// 取得全部的传入参数的数组

$args = func_get_args();

foreach ($args as $k => $v) {

echo “arg”.($k+1).”: $v\n”;

}

}

foo();

/* 什么也不会输出 */

foo(‘hello’);

/* 输出

arg1: hello

*/

foo(‘hello’, ‘world’, ‘again’);

/* 输出

arg1: hello

arg2: world

arg3: again

*/

二、使用glob()查找文件

大部分PHP函数的函数名从字面上均可以理解其用途,可是当你看到 glob() 的时候,你也许并不知道这是用来作什么的,其实glob()和scandir() 同样,能够用来查找文件,请看下面的用法:

// 取得全部的后缀为PHP的文件
$files = glob(‘*.php’);
print_r($files);
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/

你还能够查找多种后缀名:

// 取PHP文件和TXT文件
$files = glob(‘*.{php,txt}’, GLOB_BRACE);
print_r($files);
/* 输出:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
)
*/

你还能够加上路径:

$files = glob(‘../images/a*.jpg’);
print_r($files);
/* 输出:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/

若是你想获得绝对路径,你能够调用 realpath() 函数:

$files = glob(‘../images/a*.jpg’);
// applies the function to each array element
$files = array_map(‘realpath’,$files);
print_r($files);
/* output looks like:
Array
(
[0] => C:\wamp\www\images\apple.jpg
[1] => C:\wamp\www\images\art.jpg
)
*/

三、获取内存使用状况信息

PHP的内存回收机制已经很是强大,你也可使用PHP脚本获取当前内存的使用状况,调用memory_get_usage() 函数获取当期内存使用状况,调用memory_get_peak_usage() 函数获取内存使用的峰值。参考代码以下:

echo “Initial: “.memory_get_usage().” bytes \n”;
/* 输出
Initial: 361400 bytes
*/
// 使用内存
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}
// 删除一半的内存
for ($i = 0; $i < 100000; $i++) {
unset($array[$i]);
}
echo “Final: “.memory_get_usage().” bytes \n”;
/* prints
Final: 885912 bytes
*/
echo “Peak: “.memory_get_peak_usage().” bytes \n”;
/* 输出峰值
Peak: 13687072 bytes
*/

四、获取CPU使用状况信息

获取了内存使用状况,也可使用PHP的 getrusage()获取CPU使用状况,该方法在windows下不可用。

print_r(getrusage());
/* 输出
Array
(
[ru_oublock] => 0
[ru_inblock] => 0
[ru_msgsnd] => 2
[ru_msgrcv] => 3
[ru_maxrss] => 12692
[ru_ixrss] => 764
[ru_idrss] => 3864
[ru_minflt] => 94
[ru_majflt] => 0
[ru_nsignals] => 1
[ru_nvcsw] => 67
[ru_nivcsw] => 4
[ru_nswap] => 0
[ru_utime.tv_usec] => 0
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/

这个结构看上出很晦涩,除非你对CPU很了解。下面一些解释:

  • ru_oublock: 块输出操做
  • ru_inblock: 块输入操做
  • ru_msgsnd: 发送的message
  • ru_msgrcv: 收到的message
  • ru_maxrss: 最大驻留集大小
  • ru_ixrss: 所有共享内存大小
  • ru_idrss:所有非共享内存大小
  • ru_minflt: 页回收
  • ru_majflt: 页失效
  • ru_nsignals: 收到的信号
  • ru_nvcsw: 主动上下文切换
  • ru_nivcsw: 被动上下文切换
  • ru_nswap: 交换区
  • ru_utime.tv_usec: 用户态时间 (microseconds)
  • ru_utime.tv_sec: 用户态时间(seconds)
  • ru_stime.tv_usec: 系统内核时间 (microseconds)
  • ru_stime.tv_sec: 系统内核时间?(seconds)

要看到你的脚本消耗了多少CPU,咱们须要看看“用户态的时间”和“系统内核时间”的值。秒和微秒部分是分别提供的,您能够把微秒值除以100万,并把它添加到秒的值后,能够获得有小数部分的秒数。

// sleep for 3 seconds (non-busy)
sleep(3);
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* 输出
User time: 0.011552
System time: 0
*/

sleep是不占用系统时间的,咱们能够来看下面的一个例子:

// loop 10 million times (busy)
for($i=0;$i<10000000;$i++) {
}
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* 输出
User time: 1.424592
System time: 0.004204
*/

这花了大约14秒的CPU时间,几乎全部的都是用户的时间,由于没有系统调用。

系统时间是CPU花费在系统调用上的上执行内核指令的时间。下面是一个例子:

$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) – $start < 3) {
}
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* prints
User time: 1.088171
System time: 1.675315
*/

咱们能够看到上面这个例子更耗CPU。

五、获取系统常量

PHP 提供很是有用的系统常量 可让你获得当前的行号 (__LINE__),文件 (__FILE__),目录 (__DIR__),函数名 (__FUNCTION__),类名(__CLASS__),方法名(__METHOD__) 和名字空间 (__NAMESPACE__),很像C语言。

咱们能够觉得这些东西主要是用于调试,当也不必定,好比咱们能够在include其它文件的时候使用?__FILE__ (固然,你也能够在 PHP 5.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__ 来输出一些debug的信息,这样有助于你调试程序:

// some code
// …
my_debug(“some debug message”, __LINE__);
/* 输出
Line 4: some debug message
*/
// some more code
// …
my_debug(“another debug message”, __LINE__);
/* 输出
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo “Line $line: $msg\n”;
}

六、生成惟一的id

不少朋友都利用md5()来生成惟一的编号,可是md5()有几个缺点:一、无序,致使数据库中排序性能降低。二、太长,须要更多的存储空间。其实PHP中自带一个函数来生成惟一的id,这个函数就是uniqid()。下面是用法:

// generate unique string
echo uniqid();
/* 输出
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* 输出
4bd67c9472340
*/

该算法是根据CPU时间戳来生成的,因此在相近的时间段内,id前几位是同样的,这也方便id的排序,若是你想更好的避免重复,能够在id前加上前缀,如:

// 前缀
echo uniqid(‘foo_’);
/* 输出
foo_4bd67d6cd8b8f
*/
// 有更多的熵
echo uniqid(”,true);
/* 输出
4bd67d6cd8b926.12135106
*/
// 都有
echo uniqid(‘bar_’,true);
/* 输出
bar_4bd67da367b650.43684647
*/

七、序列化

PHP序列化功能你们可能用的比较多,也比较常见,当你须要把数据存到数据库或者文件中是,你能够利用PHP中的serialize() 和 unserialize()方法来实现序列化和反序列化,代码以下:

// 一个复杂的数组
$myvar = array(
‘hello’,
42,
array(1,’two’),
‘apple’
);
// 序列化
$string = serialize($myvar);
echo $string;
/* 输出
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”;}
*/
// 反序例化
$newvar = unserialize($string);
print_r($newvar);
/* 输出
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/

如何序列化成json格式呢,放心,php也已经为你作好了,使用php 5.2以上版本的用户可使用json_encode() 和 json_decode() 函数来实现json格式的序列化,代码以下:

// a complex array
$myvar = array(
‘hello’,
42,
array(1,’two’),
‘apple’
);
// convert to a string
$string = json_encode($myvar);
echo $string;
/* prints
["hello",42,[1,"two"],”apple”]
*/
// you can reproduce the original variable
$newvar = json_decode($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/

八、字符串压缩

当咱们说到压缩,咱们可能会想到文件压缩,其实,字符串也是能够压缩的。PHP提供了 gzcompress() 和gzuncompress() 函数:

$string =
“Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. “;
$compressed = gzcompress($string);
echo “Original size: “. strlen($string).”\n”;
/* 输出原始大小
Original size: 800
*/
echo “Compressed size: “. strlen($compressed).”\n”;
/* 输出压缩后的大小
Compressed size: 418
*/
// 解压缩
$original = gzuncompress($compressed);

几乎有50% 压缩比率。同时,你还可使用 gzencode() 和 gzdecode() 函数来压缩,只不用其用了不一样的压缩算法。

以上就是8个开发必备的PHP功能,是否是都很实用呢?

相关文章
相关标签/搜索