搜索
首页后端开发php教程9个实用的PHP函数_PHP教程
9个实用的PHP函数_PHP教程Jul 21, 2016 pm 02:53 PM
php了解使用函数功能发现多年实际的

  即使使用 PHP 多年,也会偶然发现一些未曾了解的函数和功能。其中有些是非常有用的,但没有得到充分利用。并不是所有人都会从头到尾一页一页地阅读手册和函数参考!

  1、任意参数数目的函数

  你可能已经知道,PHP 允许定义可选参数的函数。但也有完全允许任意数目的函数参数的方法。以下是可选参数的例子:

  // function with 2 optional arguments

  function foo($arg1 = '', $arg2 = '') {

  echo "arg1: $arg1n";

  echo "arg2: $arg2n";

  }

  foo('hello','world');

  /* prints:

  arg1: hello

  arg2: world

  */

  foo();

  /* prints:

  arg1:

  arg2:

  */

  现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用 func_get_args() 函数:

  // yes, the argument list can be empty

  function foo() {

  // returns an array of all passed arguments

  $args = func_get_args();

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

  echo "arg".($k+1).": $vn";

  }

  }

  foo();

  /* prints nothing */

  foo('hello');

  /* prints

  arg1: hello

  */

  foo('hello', 'world', 'again');

  /* prints

  arg1: hello

  arg2: world

  arg3: again

  */

  2、使用 Glob() 查找文件

  许多 PHP 函数具有长描述性的名称。然而可能会很难说出 glob() 函数能做的事情,除非你已经通过多次使用并熟悉了它。可以把它看作是比 scandir() 函数更强大的版本,可以按照某种模式搜索文件。

  // get all php files

  $files = glob('*.php');

  print_r($files);

  /* output looks like:

  Array

  (

  [0] => phptest.php

  [1] => pi.php

  [2] => post_output.php

  [3] => test.php

  )

  */

  你可以像这样获得多个文件:

  // get all php files AND txt files

  $files = glob('*.{php,txt}', GLOB_BRACE);

  print_r($files);

  /* output looks like:

  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);

  /* output looks like:

  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:wampwwwimagesapple.jpg

  [1] => C:wampwwwimagesart.jpg

  )

  */

  3、内存使用信息

  通过侦测脚本的内存使用情况,有利于代码的优化。PHP 提供了一个垃圾收集器和一个非常复杂的内存管理器。脚本执行时所使用的内存量,有升有跌。为了得到当前的内存使用情况,我们可以使用 memory_get_usage() 函数。如果需要获得任意时间点的最高内存使用量,则可以使用 memory_limit() 函数。

  echo "Initial: ".memory_get_usage()." bytes n";

  /* prints

  Initial: 361400 bytes

  */

  // let's use up some memory

  for ($i = 0; $i

  $array []= md5($i);

  }

  // let's remove half of the array

  for ($i = 0; $i

  unset($array[$i]);

  }

  echo "Final: ".memory_get_usage()." bytes n";

  /* prints

  Final: 885912 bytes

  */

  echo "Peak: ".memory_get_peak_usage()." bytes n";

  /* prints

  Peak: 13687072 bytes

  */

  4、CPU 使用信息

  为此,我们要利用 getrusage() 函数。请记住这个函数不适用于 Windows 平台。

  print_r(getrusage());

  /* prints

  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

  )

  */

  这可能看起来有点神秘,除非你已经有系统管理员权限。以下是每个值的具体说明(你不需要记住这些):

  ru_oublock: block output operations

  ru_inblock: block input operations

  ru_msgsnd: messages sent

  ru_msgrcv: messages received

  ru_maxrss: maximum resident set size

  ru_ixrss: integral shared memory size

  ru_idrss: integral unshared data size

  ru_minflt: page reclaims

  ru_majflt: page faults

  ru_nsignals: signals received

  ru_nvcsw: voluntary context switches

  ru_nivcsw: involuntary context switches

  ru_nswap: swaps

  ru_utime.tv_usec: user time used (microseconds)

  ru_utime.tv_sec: user time used (seconds)

  ru_stime.tv_usec: system time used (microseconds)

  ru_stime.tv_sec: system time used (seconds)

  要知道脚本消耗多少 CPU 功率,我们需要看看 ‘user time’ 和 ’system time’ 两个参数的值。秒和微秒部分默认是单独提供的。你可以除以 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);

  /* prints

  User time: 0.011552

  System time: 0

  */

  尽管脚本运行用了大约 3 秒钟,CPU 使用率却非常非常低。因为在睡眠运行的过程中,该脚本实际上不消耗 CPU 资源。还有许多其他的任务,可能需要一段时间,但不占用类似等待磁盘操作等 CPU 时间。因此正如你所看到的,CPU 使用率和运行时间的实际长度并不总是相同的。下面是一个例子:

  // loop 10 million times (busy)

  for($i=0;$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);

  /* prints

  User time: 1.424592

  System time: 0.004204

  */

  这花了大约 1.4 秒的 CPU 时间,但几乎都是用户时间,因为没有系统调用。系统时间是指花费在执行程序的系统调用时的 CPU 开销。下面是一个例子:

  $start = microtime(true);

  // keep calling microtime for about 3 seconds

  while(microtime(true) - $start

  }

  $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

  */

  现在我们有相当多的系统时间占用。这是因为脚本多次调用 microtime() 函数,该函数需要向操作系统发出请求,以获取所需时间。你也可能会注意到运行时间加起来不到 3 秒。这是因为有可能在服务器上同时存在其他进程,并且脚本没有 100% 使用 CPU 的整个 3 秒持续时间。

  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: $msgn";

  }

  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() 更短的字符串,能节省一些空间。

  7、序列化

  你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP 已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用 serialize() 和 unserialize() 函数:

  // a complex array

  $myvar = array(

  'hello',

  42,

  array(1,'two'),

  'apple'

  );

  // convert to a string

  $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";}

  */

  // you can reproduce the original variable

  $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() 函数:

  // 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

  )

  */

  这将更为行之有效,尤其与 JavaScript 等许多其他语言兼容。然而对于复杂的对象,某些信息可能会丢失。

  8、压缩字符串

  在谈到压缩时,我们通常想到文件压缩,如 ZIP 压缩等。在 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";

  /* prints

  Original size: 800

  */

  echo "Compressed size: ". strlen($compressed)."n";

  /* prints

  Compressed size: 418

  */

  // getting it back

  $original = gzuncompress($compressed);

  这种操作的压缩率能达到 50% 左右。另外的函数 gzencode() 和 gzdecode() 能达到类似结果,通过使用不同的压缩算法。

  9、注册停止功能

  有一个函数叫做 register_shutdown_function(),可以让你在某段脚本完成运行之前,执行一些指定代码。假设你需要在脚本执行结束前捕获一些基准统计信息,例如运行的时间长度:

  // capture the start time

  $start_time = microtime(true);

  // do some stuff

  // ...

  // display how long the script took

  echo "execution took: ".

  (microtime(true) - $start_time).

  " seconds.";

  这似乎微不足道,你只需要在脚本运行的最后添加相关代码。但是如果你调用过 exit() 函数,该代码将无法运行。此外,如果有一个致命的错误,或者脚本被用户意外终止,它可能无法再次运行。当你使用 register_shutdown_function() 函数,代码将继续执行,不论脚本是否停止运行:

  $start_time = microtime(true);

  register_shutdown_function('my_shutdown');

  // do some stuff

  // ...

  function my_shutdown() {

  global $start_time;

  echo "execution took: ".

  (microtime(true) - $start_time).

  " seconds.";

  }

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/371403.htmlTechArticle即使使用 PHP 多年,也会偶然发现一些未曾了解的函数和功能。其中有些是非常有用的,但没有得到充分利用。并不是所有人都会从头到尾...
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

地理信息科学专业学生应选择哪种电脑地理信息科学专业学生应选择哪种电脑Jan 13, 2024 am 08:00 AM

推荐适合地理信息科学专业学生用的电脑1.推荐2.地理信息科学专业学生需要处理大量的地理数据和进行复杂的地理信息分析,因此需要一台性能较强的电脑。一台配置高的电脑可以提供更快的处理速度和更大的存储空间,能够更好地满足专业需求。3.推荐选择一台配备高性能处理器和大容量内存的电脑,这样可以提高数据处理和分析的效率。此外,选择一台具备较大存储空间和高分辨率显示屏的电脑也能更好地展示地理数据和结果。另外,考虑到地理信息科学专业学生可能需要进行地理信息系统(GIS)软件的开发和编程,选择一台支持较好的图形处

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。