内存使用情况
memory_get_usage()
echo '开始内存:'.memory_get_usage(), '';
$tmp = str_repeat('hello', 1000);
echo '运行后内存:'.memory_get_usage(), '';
unset($tmp);
echo '回到正常内存:'.memory_get_usage();
isset
isset ( mixed $var [, mixed $... ] ) : bool
Determine if a variable is considered set, this means if a variable is declared and is different than NULL.
If a variable has been unset with the unset() function, it is no longer considered to be set.
isset() will return FALSE when checking a variable that has been assigned to NULL
. Also note that a null character ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are considered set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
PHP接收表单(GET/POST)时,表单名中的点变成了下划线
@
(object)[]
声明空对象, json_encode
(object)[]
可以得到 {}
()->{}()
$ret = (new $class)->{$method}($signature);
class AAAA {
public function __construct()
{
echo 'I am AAAA';
}
public function test($a)
{
echo 'I am test:' . $a;
}
}
$class = "AAAA";
$method = 'test';
$signature = 'signature';
$ret = (new $class)->{$method}($signature);
...
可以打包参数 和 解包参数
Event::fire('addApiLog', $api, $post, $resp_data);
public static function fire($event, ...$args)
{
$rets = [];
foreach (static::$events[$event] as $k => $ev) {
if (is_callable($ev)) {
$rets[$k] = $ev(...$args);
}
}
return $rets;
}
[] & {}
方括号和花括号可以互换使用来访问数组单元(例如 $array[42] 和 $array{42} 效果相同)。
**
$a = 2;
$b = 4;
$d = $a ** $b;
answer
16
??
The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise. ==In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.==
$this->action['as'] ?? null;
$this->action['controller'] ?? 'Closure';
$this->action['middleware'] ?? []
$last['prefix'] ?? ''
A
array_reduce
array_reduce($arr, $function)
将回调函数function迭代的作用到每一个单元中
$a = [100, 200, 300];
var_dump(array_reduce($a, function sum($carry, $item)
{
$carry += $item;
return $carry;
}));
array_walk_recursive
array_walk_recursive ( array &$input , callable $funcname [, mixed $userdata = NULL ] )
将用户自定义函数 funcname 应用到 array 数组中的每个单元。本函数会递归到更深层的数组中去。
array_merge
如果和 null merge 则会 merge为null
array_filter
将传入的数组的每一个值传递到callback中如果为true
则输入的数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。
array_values
返回所有值 不保留键名,从0开始以1递增
只改变最外围的键名
例:
$a = array(
'parent'=>array(
'son'=>array('son1','son2')
),
'parent2'=>'parent2');
);
var_dump(array_values($a)
array(2) {
[0]=>
array(1) {
["son"]=>
array(2) {
[0]=>
string(4) "son1"
[1]=>
string(4) "son2"
}
}
[1]=>
string(7) "parent2"
}
B
base64
public function handleLogo() {
$logo = $this->input("logo");
if ($logo) {
if (preg_match('/^(data:\s*image\/(.+);base64,)/', $logo, $result)) {
$img = base64_decode(str_replace($result[1], '', $logo));
$type = $result[2];
$img_path = Rule::LOGO_PATH . time() . uniqid("r") . '.' . $type;
if (!Storage::disk(Rule::DISK)->put($img_path, $img)) {
throw CustomException::Gen("LOGO上传失败");
}
$this->merge(["logo" => Storage::disk("public")->url($img_path)]);
} else if (strpos($logo, "/storage/logo") !== false) {
$this->merge(["logo" => $logo]);
} else {
throw CustomException::Gen("图片格式有误");
}
}
}
C
compact
$a = 1;
$b = 2;
$c = compact('a', 'b');
dd($c);
打印结果如下
array:2 [
"a" => 1
"b" => 2
]
checkdnsrr
根据一个给定的hostname(域名)或者IP地址检查它是否有DNS记录,其实也就是检验它是否存在。
checkdnsrr('www.baidu.com')
call_user_func_array
调用回调函数,并把一个数组参数作为回调函数的参数
详情查看手册中示例
Example#1 call_user_func_array() 例子
Example#2 call_user_func_array() 使用命名空间的情况
count
统计数组的长度(只计算最外层)
count($a, 1);
统计多维数组 统计每个维度的长度并相加算总和
count($a, 0);
不统计多维 只计算第一维
if (count($array) == count($array, 1)) {
echo '是一维数组';
} else {
echo '不是一维数组';
}
D
debug_backtrace
产生一条回溯跟踪
defind
defind(‘需要检测的常量名’)
defined — Checks whether a given named constant exists
E
error_reporting
// 关闭所有PHP错误报告
error_reporting ( 0 );
// Report simple running errors
error_reporting ( E_ERROR | E_WARNING | E_PARSE );
// 报告 E_NOTICE也挺好 (报告未初始化的变量
// 或者捕获变量名的错误拼写)
error_reporting ( E_ERROR | E_WARNING | E_PARSE | E_NOTICE );
// 除了 E_NOTICE,报告其他所有错误
// 这是在 php.ini 里的默认设置
error_reporting ( E_ALL ^ E_NOTICE );
// 报告所有 PHP 错误 (参见 changelog)
error_reporting ( E_ALL );
// 报告所有 PHP 错误
error_reporting (- 1 );
// 和 error_reporting(E_ALL); 一样
ini_set ( 'error_reporting' , E_ALL );
extract
extract — Import variables into the current symbol table from an array
将数组中的键值复制给键名
<?php
$size = "large";
$var_array =[
"color" => "blue",
"size" => "medium",
"shape" => "sphere"
];
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>
exec
exec(
$command
,$output
,$return
)
命令: eg. whoami(linux 命令)
$output 命令执行的输出填充此数组
$return 命令执行后的返回状态会被写入到此变量 (0 为成功状态)
F
filesize
获取文件大小
fopen
打开文件或者URL
a
写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之
fputcsv
fputcsv($fp, $data, ',', '"');
handle
文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。
fields
值的一个数组。
delimiter
可选的 delimiter 参数设定字段分界符(只允许一个字符)。
enclosure
可选的 enclosure 参数设定字段字段环绕符(只允许一个字符)。
func_get_args
获取参数列表
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs \n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
foo(1, 2, 3);
?>
The above example will output:
Number of arguments: 3
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3
foreach
强制类型 (array)
foreach ((array) $paths as $path) {
$migrator->path($path);
}
G
gethostname
gets the standard host name for the local machine.
>>> gethostname()
=> "AnnadeMacBook-Pro.local"
getmypid
Gets PHP's process ID
H
http_build_query
使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。
$a = array(1, 2, 3);
echo http_build_query($a);
>>> 0=1&1=2&2=3
$a = array('a'=>1, 'b'=>2, 'c'=>3);
echo http_build_query($a);
>>> a=1&b=2&c=3
I
isset
➜ tmp php -a
Interactive shell
php > $a = null; echo strlen($a);
0
php > var_dump(isset($a));
bool(false)
php >
is_readable
判断给定的文件名是否可读
ini_set
ini_set(string $varname, string $newvalue)
设置指定配置选项的值,这个选项会在脚本运行时保持新的值,并在脚本结束时恢复
J
json_encode
如果$a是非索引数组,在js中就会是对象,如果是索引数组,js中是数组 第一个索引始终是数字 0,且添加到数组中的每个后续元素的索引以 1 为增量递增 这种数组才是索引数组,不连续的数字键名不算是索引数组,是关联数组
K
L
list
list() only works on numerical arrays and assumes the numerical indices start at 0.
M
move_uploaded_file
- enctype="multipart/form-data"
- move_uploaded_file
/Users/Anna/wwwroot/anna-php/Test/Test2/test.php:31:
array (size=5)
'name' => string '童年·田字格.mssf' (length=22)
'type' => string 'application/octet-stream' (length=24)
'tmp_name' => string '/private/var/tmp/phpM0O8EW' (length=26)
'error' => int 0
'size' => int 26247
//代码
<form action="store" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="">
<br>
<button type="submit">提交</button>
</form>
$file = $_FILES['file'];
var_dump($file);
$ret = move_uploaded_file($file['tmp_name'], APP_PATH . $file['name']);
mt_rand
mt_rand() 比rand() 快四倍
mb_detect_encoding
获取字符串的编码格式
N
O
operate
操作符优先级(高到低)
++ --
!
乘除
加减
各种大小于
各种等于
&& ||
各种赋值
字母版 && ||
P
PHP_EOL
相当于换行符
在unix系列用 \n
在windows系列用 \r\n
在mac用 \r
parse_str & parse_url
sample.com?a=1&b=2&c=3
parse_str(parse_url($url)['query'], $query);
>>> parse_url('sample.com?a=1&b=2&c=3')
=> [
"path" => "sample.com",
"query" => "a=1&b=2&c=3",
]
>>> parse_str(parse_url('sample.com?a=1&b=2&c=3')['query'], $query)
>>> dump($query)
=> [
"a" => "1",
"b" => "2",
"c" => "3",
]
pack
Pack data into binary string
pack ( string $format [, mixed $args [, mixed $... ]] )
preg_match
preg_replace_callback
将十六进制转义序列转换成字符串
function hextostr($hex)
{
return preg_replace_callback('/\\\x([0-9a-fA-F]{2})/', function($matches) {
return chr(hexdec($matches[1]));
}, $hex);
}
proc_open
Execute a command and open file pointers for input/output
resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )
Q
R
urlencode
>>> rawurlencode(' ')
=> "%20"
>>> urlencode(' ')
=> "+"
register_shutdown_function
register_shutdown_function("shutdown_func")
shutdown_func将会调用的函数
当脚本执行完成或意外死掉导致php执行即将关闭时,这个函数将会被调用
执行机制:php将要调用的函数调入内存,当页面所有php语句都执行完成时,再调用此函数。(注意,这个时候从内存中调用,不是从php野蛮中调用,所以不能使用相对路径,因为php已经当原来的页面不存在了)
S
strlen
➜ tmp php -a
Interactive shell
php > $a = null; echo strlen($a);
0
php > var_dump(isset($a));
bool(false)
php >
sftp
需要安装扩展
$connection = ssh2_connect('shell.example.com', 22);
if (ssh2_auth_password($connection, 'username', 'secret')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
strval
将变量以字符串方式返回
class StrValTest
{
public function __toString()
{
return __CLASS__;
}
}
// Prints 'StrValTest'
echo strval(new StrValTest);
spl_autoload_register
<?php
// function __autoload($class) {
// include 'classes/' . $class . '.class.php';
// }
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
?>
serialize
检查类中是否有魔术名称 sleep 的函数。如果这样,该函数将在任何序列化之前运行。它可以清除对象并应该返回一个包含有该对象中应被序列化的所有变量名的数组。 使用 sleep 的目的是关闭对象可能具有的任何数据库连接,提交等待中的数据或进行类似的清除任务。此外,如果有非常大的对象而并不需要完全储存下来时此函数也很有用。
class Courier {
public $name;
public $home_country;
public function __construct($name, $home_country) {
$this->name = $name;
$this->home_country = $home_country;
$this->logfile = $this->getLogFile();
return true;
}
protected function getLogFile() {
// error log location would be in a config file
return fopen('/tmp/error_log.txt', 'a');
}
public function log($message) {
if($this->logfile) {
fputs($this->logfile, 'Log message: ' . $message . "\n");
}
}
public function __sleep() {
// only store the "safe" properties
return array("name", "home_country");
}
public function __wakeup() {
// properties are restored, now add the logfile
$this->logfile = $this->getLogFile();
return true;
}
SplFileObject
php读取大文件的类
$fp = new SplFileObject($filename, $method);
$fp->seek($starLine-1)转到指定行,seek方法从0开始计数
$fp->fgetcsv() //获取一行csv并以数组形式返回
$fp->eof() 文件到末尾返回真 否则返回假
set_time_limit
set_time_limit(int $seconds)
设置脚本最大的执行时间,单位为秒。 若设置为0, 没有时间限制
strpos
- 不存在的判断方法
- 因为字符串的起始位置是0!!!
if (strpos($sql_formed, 'limit') === false && strpos($sql_formed, 'select') !== false) {
$sql_formed .= ' limit 20';
}
spl_object_hash
Return hash id for given object
spl_object_hash()
stream_socket_sendto
Sends a message to a socket, whether it is connected or not
int stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string $address ]] )
stream_get_contents
stream_get_contents — Reads remainder of a stream into a string
string stream_get_contents ( resource $handle [, int $maxlength = -1 [, int $offset = -1 ]] )
sprintf
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
可以避免命令出错
return sprintf('git clone --mirror %s %s', $url, $dir);
T
U
rawurlencode & urlencode
>>> rawurlencode(' ')
=> "%20"
>>> urlencode(' ')
=> "+"
unserialize
检查具有魔术名称 wakeup 的函数的存在。如果存在,此函数可以重建对象可能具有的任何资源。 使用 wakeup 的目的是重建在序列化中可能丢失的任何数据库连接以及处理其它重新初始化的任务。
unset
可以一下子unset掉多个
unset($a, $b, $c);
V
version_compare
version_compare('php的版本号',’PHP的版本号‘)
如果第一个版本号小于第二个版本号 返回-1 相等返回0 第一个版本大于第二个版本时返回1 (还有第三个可选参数)
var_export
返回合法的PHP代码 如果函数的第二个参数设置为TRUE,不会直接打印出字符串,而是将值传给一个变量,然后使用echo输出