8 个必备的PHP功能开发_PHP教程
做过PHP开发的程序员应该清楚,PHP中有很多内置的功能,掌握了它们,可以帮助你在做PHP开发时更加得心应手,本文将分享8个开发必备的PHP功能,个个都非常实用,希望各位PHP开发者能够掌握。
1、传递任意数量的函数参数
我们在.NET或者JAVA编程中,一般函数参数个数都是固定的,但是PHP允许你使用任意个数的参数。下面这个示例向你展示了PHP函数的默认参数:
Php代码
- // 两个默认参数的函数
- function foo($arg1 = ”, $arg2 = ”) {
- echo “arg1: $arg1\n”;
- echo “arg2: $arg2\n”;
- }
- foo(‘hello’,'world’);
- /* 输出:
- arg1: hello
- arg2: world
- */
- foo();
- /* 输出:
- arg1:
- arg2:
- */
- 下面这个示例是PHP的不定参数用法,其使用到了 [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url]方法:
- // 是的,形参列表为空
- 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
- */
- // 取得所有的后缀为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
- )
- */
- $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
- )
- */
- echo “Initial: “.memory_get_usage().” bytes \n”;
- /* 输出
- Initial: 361400 bytes
- */
- // 使用内存
- for ($i = 0; $i
- $array []= md5($i);
- }
- // 删除一半的内存
- 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”;
- /* 输出峰值
- Peak: 13687072 bytes
- */
- 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
- )
- */
- 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)
- // 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
- */
- // 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);
- /* 输出
- User time: 1.424592
- System time: 0.004204
- */
- $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
- */
- // 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’);
- // 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”;
- }
- // generate unique string
- echo uniqid();
- /* 输出
- 4bd67c947233e
- */
- // generate another unique string
- echo uniqid();
- /* 输出
- 4bd67c9472340
- */
- // 前缀
- echo uniqid(‘foo_’);
- /* 输出
- foo_4bd67d6cd8b8f
- */
- // 有更多的熵
- echo uniqid(”,true);
- /* 输出
- 4bd67d6cd8b926.12135106
- */
- // 都有
- echo uniqid(‘bar_’,true);
- /* 输出
- bar_4bd67da367b650.43684647
- */
- // 一个复杂的数组
- $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
- )
- */
- // 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
- )
- */
- $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);
原文出处:8个开发必备的PHP功能

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 여러 라이브러리가 있습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다
