Gor*_*don 4314 php arguments symbols operators
This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.
It used to be hard to find questions about operators and other syntax tokens.¹
The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the PHP Manual.
Note: Since January 2013, Stack Overflow does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="
如果您因为提出这样的问题而被某人指向此处,请在下面找到具体的语法.PHP手册的链接页面以及链接的问题可能会回答您的问题.如果是这样,我们鼓励您提出答案.此列表并不代替其他人提供的帮助.
如果您的特定令牌未在下面列出,您可能会在" 解析器令牌列表"中找到它.
=&
参考
&=
按位运算符
&&
逻辑运算符
%
算术运算符
??
Null Coalesce Operator (since PHP 7)
?string
?int
?array
?bool
?float
Nullable return type declaration (since PHP 7.1)
:
Alternative syntax for control structures, Ternary Operator
=>
Arrays
<=>
Comparison Operators (since PHP 7.0)
+
Arithmetic Operators, Array Operators
+=
and -=
Assignment Operators
++
and --
Incrementing/Decrementing Operators
<?=
Short Open Tags
[]
Arrays (short syntax since PHP 5.4)
Pet*_*tai 1109
++
增量运算符
--
递减算子
Example Name Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Run Code Online (Sandbox Code Playgroud)
这些可以在变量之前或之后.
如果变量之前说,该递增/递减操作完成的变量第一,然后返回结果.如果放在变量之后,首先返回变量,然后完成递增/递减操作.
例如:
$apples = 10;
for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}
Run Code Online (Sandbox Code Playgroud)
在使用上面的情况下++$i
,因为它更快.$i++
会有相同的结果.
预增量稍微快一些,因为它确实增加了变量,然后'返回'结果.后增量创建一个特殊变量,在那里复制第一个变量的值,并且只有在使用第一个变量之后,才用第二个变量替换它的值.
但是,您必须使用$apples--
,因为首先,您要显示当前的苹果数,然后您想从中减去一个苹果.
您还可以在PHP中增加字母:
$i = "a";
while ($i < "c") {
echo $i++;
}
Run Code Online (Sandbox Code Playgroud)
下一次z
到达aa
,依此类推.
请注意,字符变量可以递增但不递减,即使只支持纯ASCII字符(az和AZ).
Stack Overflow帖子:
Ank*_*ena 424
有点什么?位是1或0的表示.基本上为OFF(0)和ON(1)
什么是字节?一个字节由8位组成,一个字节的最高值为255,这意味着每个位都被置位.我们将看看为什么字节的最大值是255.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
Run Code Online (Sandbox Code Playgroud)
这个1字节的表示
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255(1字节)
&
$a = 9;
$b = 10;
echo $a & $b;
Run Code Online (Sandbox Code Playgroud)
这会输出数字8.为什么?好吧,让我们看一下使用我们的表格示例.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| & | 0| 0| 0| 0| 1| 0| 0| 0|
-------------------------------------------
Run Code Online (Sandbox Code Playgroud)
所以你可以从表中看到他们共享的唯一位是8位.
第二个例子
$a = 36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111
Run Code Online (Sandbox Code Playgroud)
两个共享位是32和4,当它们加在一起时返回36.
|
$a = 9;
$b = 10;
echo $a | $b;
Run Code Online (Sandbox Code Playgroud)
这将输出数字11.为什么?
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| | | 0| 0| 0| 0| 1| 0| 1| 1|
-------------------------------------------
Run Code Online (Sandbox Code Playgroud)
您会注意到我们在8列,2列和1列中设置了3位.添加它们:8 + 2 + 1 = 11.
Ank*_*ena 262
Syntax Name Description
x == y Equality True if x and y have the same key/value pairs
x != y Inequality True if x is not equal to y
x === y Identity True if x and y have the same key/value pairs
in the same order and of the same types
x !== y Non-identity True if x is not identical to y
++ x Pre-increment Increments x by one, then returns x
x ++ Post-increment Returns x, then increments x by one
-- x Pre-decrement Decrements x by one, then returns x
x -- Post-decrement Returns x, then decrements x by one
x and y And True if both x and y are true x=6 y=3
(x < 10 and y > 1) returns true
x && y And True if both x and y are true x=6 y=3
(x < 10 && y > 1) returns true
a . b Concatenation Concatenate two strings: "Hi" . "Ha"
Run Code Online (Sandbox Code Playgroud)
She*_*rif 261
<=>
宇宙飞船运营商该飞船操作 <=>
是在PHP 7增加了最新的运营商相比,它是一种非关联二元运算符具有相同优先级的平等运算符(==
,!=
,===
,!==
).该运算符允许在左手操作数和右手操作数之间进行更简单的三向比较.
运算符导致整数表达式为:
0
当两个操作数相等时0
左操作数小于右操作数的时候0
左侧操作数大于右侧操作数的时间例如
1 <=> 1; // 0
1 <=> 2; // -1
2 <=> 1; // 1
Run Code Online (Sandbox Code Playgroud)
使用此运算符的一个很好的实际应用是比较类型的回调,预期基于两个值之间的三向比较返回零,负或正整数.传递给的比较函数usort
就是一个这样的例子.
$arr = array(4,2,1,3);
usort($arr, function ($a, $b) {
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
});
Run Code Online (Sandbox Code Playgroud)
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
return $a <=> $b;
});
Run Code Online (Sandbox Code Playgroud)
Sum*_*and 230
魔术常数:虽然这些不仅仅是符号,而是这个象征家族的重要组成部分.有八个魔法常数会根据它们的使用位置而改变.
__LINE__
:文件的当前行号.
__FILE__
:文件的完整路径和文件名.如果在include中使用,则返回包含文件的名称.从PHP 4.0.2开始,__FILE__
始终包含已解析符号链接的绝对路径,而在旧版本中,它在某些情况下包含相对路径.
__DIR__
:文件的目录.如果在include中使用,则返回包含文件的目录.这相当于dirname(__FILE__)
.除非它是根目录,否则此目录名称没有尾部斜杠.(在PHP 5.3.0中添加.)
__FUNCTION__
:函数名称.(在PHP 4.3.0中添加)从PHP 5开始,此常量返回声明的函数名称(区分大小写).在PHP 4中,它的值总是小写的.
__CLASS__
:班级名称.(在PHP 4.3.0中添加)从PHP 5开始,此常量返回声明的类名(区分大小写).在PHP 4中,它的值总是小写的.类名包括它声明的名称空间(例如Foo\Bar
).请注意,从PHP 5.4开始,它__CLASS__
也适用于特征.在trait方法中使用时,__CLASS__
是使用特征的类的名称.
__TRAIT__
:特征名称.(在PHP 5.4.0中添加)从PHP 5.4开始,此常量返回声明的特征(区分大小写).特征名称包括声明它的名称空间(例如Foo\Bar
).
__METHOD__
:类方法名称.(在PHP 5.0.0中添加)方法名称在声明时返回(区分大小写).
__NAMESPACE__
:当前命名空间的名称(区分大小写).此常量在编译时定义(在PHP 5.3.0中添加).
Mau*_*tel 146
instanceof
用于确定PHP变量是否是某个类的实例化对象.
<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
Run Code Online (Sandbox Code Playgroud)
上面的例子将输出:
bool(true)
bool(false)
Run Code Online (Sandbox Code Playgroud)
原因:上面的例子$a
是一个对象,mclass
所以只使用一个mclass
非实例的数据sclass
<?php
class pclass { }
class childclass extends pclass { }
$a = new childclass;
var_dump($a instanceof childclass);
var_dump($a instanceof pclass);
Run Code Online (Sandbox Code Playgroud)
上面的例子将输出:
bool(true)
bool(true)
Run Code Online (Sandbox Code Playgroud)
<?php
class cloneable { }
$a = new cloneable;
$b = clone $a;
var_dump($a instanceof cloneable);
var_dump($b instanceof cloneable);
Run Code Online (Sandbox Code Playgroud)
上面的例子将输出:
bool(true)
bool(true)
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 128
and
运算符和or
运算符的优先级低于赋值运算符=
.
这意味着$a = true and false;
相当于($a = true) and false
.
在大多数情况下,您可能希望使用&&
and ||
,其行为方式可以从C,Java或JavaScript等语言中获得.
raj*_*pta 99
<=>
(PHP 7中添加)<=>
Spaceship运算符的示例(PHP 7,来源:PHP手册):
整数,浮点数,字符串,数组和对象用于变量的三向比较.
// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Comparison is case-sensitive
echo "B" <=> "a"; // -1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
Run Code Online (Sandbox Code Playgroud)
mnv*_*mnv 69
{}
大括号
关于最后一篇文章的一些话
$x[4] = 'd'; // it works
$x{4} = 'd'; // it works
$echo $x[4]; // it works
$echo $x{4}; // it works
$x[] = 'e'; // it works
$x{} = 'e'; // does not work
$x = [1, 2]; // it works
$x = {1, 2}; // does not work
echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work
echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works
Run Code Online (Sandbox Code Playgroud)
VIP*_*ROY 62
空结合运算符(??)
此操作符已在PHP 7.0中添加,用于需要使用三元运算符的常见情况isset()
.它返回第一个操作数(如果存在且不存在)NULL
; 否则返回第二个操作数.
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
Run Code Online (Sandbox Code Playgroud)
dev*_*pro 59
PHP字符串: PHP字符串可以通过四种方式指定,而不仅仅是两种方式:
1)单引号字符串:
$string = 'This is my string'; // print This is my string
Run Code Online (Sandbox Code Playgroud)
2)双引号字符串:
$str = 'string';
$string = "This is my $str"; // print This is my string
Run Code Online (Sandbox Code Playgroud)
3)Heredoc:
$string = <<<EOD
This is my string
EOD; // print This is my string
Run Code Online (Sandbox Code Playgroud)
4)Nowdoc(自PHP 5.3.0起):
$string = <<<'END_OF_STRING'
This is my string
END_OF_STRING; // print This is my string
Run Code Online (Sandbox Code Playgroud)
Web*_*eng 44
题:
什么=>
意思?
回答:
=>
我们人类决定使用的符号来分离"Key" => "Value"
关联数组中的对.
阐述:
要理解这一点,我们必须知道关联数组是什么.当传统程序员想到一个数组(在PHP中)时出现的第一件事就是类似于:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Run Code Online (Sandbox Code Playgroud)
如果我们想在代码的后面部分调用数组,我们可以这样做:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.然而,作为人类,我们可能会发现很难记住,指数[0]
数组是值一年 2016年,指数[1]
的阵列是一个问候,和索引[2]
数组是一个简单的整数值.我们将拥有的另一种选择是使用所谓的关联数组.关联数组与顺序数组有一些差异
(这是先前的情况,因为它们增加了预定序列中使用的索引,通过对每个后续值递增1).
差异(顺序和关联数组之间):
在引用关联数组的过程中,您不仅要包含value
要放入数组中的内容,还要在下一部分key
调用数组时放置要使用的索引值(称为).码.在声明期间使用以下语法:"key" => "value"
.
使用关联数组时,该key
值将放在数组的索引中以检索所需的值value
.
例如:
$myArray1 = array(
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33);//option 1
$myArray2 = [
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33];//option 2
$myArray3 = [];//option 3
$myArray3["Year"] = 2016;
$myArray3["Greetings"] = "hello";
$myArray3["Integer_value"] = 33;
Run Code Online (Sandbox Code Playgroud)
现在,要获得与以前相同的输出,该key
值将用于数组索引:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
Run Code Online (Sandbox Code Playgroud)
最后一点:
因此,从上面的例子中,很容易看出该=>
符号用于表示数组中每个数组key
和数组之间的关联数组的关系.value
在数组内的值的启动期间.
dev*_*raj 34
问题:
PHP中的"&"是什么意思?
一旦我们习惯了,生活会变得更轻松..(仔细查看下面的例子)
&通常检查设置在$ a和$ b中的位.
你有没有注意到这些电话如何运作?
error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);
Run Code Online (Sandbox Code Playgroud)
所以上面的所有内容都是按位运算符和位的游戏.
其中一个有用的例子是简单的配置,如下面给出的,所以一个整数字段可以为你存储数千个组合.
大多数人已经阅读过这些文档,但没有说明这些按位运算符的实际用例.
<?php
class Config {
// our constants must be 1,2,4,8,16,32,64 ....so on
const TYPE_CAT=1;
const TYPE_DOG=2;
const TYPE_LION=4;
const TYPE_RAT=8;
const TYPE_BIRD=16;
const TYPE_ALL=31;
private $config;
public function __construct($config){
$this->config=$config;
if($this->is(Config::TYPE_CAT)){
echo 'cat ';
}
if($this->is(Config::TYPE_DOG)){
echo 'dog ';
}
if($this->is(Config::TYPE_RAT)){
echo 'rat ';
}
if($this->is(Config::TYPE_LION)){
echo 'lion ';
}
if($this->is(Config::TYPE_BIRD)){
echo 'bird ';
}
echo "\n";
}
private function is($value){
return $this->config & $value;
}
}
new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird
Run Code Online (Sandbox Code Playgroud)
小智 27
==
用于检查相等性而不考虑可变数据类型
===
用于检查平等两个变量值*和**数据类型
$a = 5
if ($a == 5)
- 将评估为真
if ($a == '5')
- 将评估为true,因为在比较这两个值时,php会在内部将该字符串值转换为整数,然后比较这两个值
if ($a === 5)
- 将评估为真
if ($a === '5')
- 将评估为false,因为value为5,但此值5不是整数.
Yog*_*cha 24
不是运营商最糟糕的名字,但PHP 7引入了相当方便的空合并,所以我想我会分享一个例子.
在PHP 5中,我们已经有一个三元运算符,它测试一个值,然后返回第二个元素,如果返回true,则返回第三个元素,如果不是:
echo $count ? $count : 10; // outputs 10
Run Code Online (Sandbox Code Playgroud)
还有一个简写,它允许你跳过第二个元素,如果它与第一个元素相同:echo $ count?:10; //也输出10
在PHP 7中我们另外得到?? 运算符,而不是表示极端混乱,而不是我通常会一起使用两个问号,而是允许我们将一串值链接在一起.从左到右读取,存在且不为null的第一个值是将返回的值.
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
Run Code Online (Sandbox Code Playgroud)
此构造对于为来自用户输入或现有配置的一个或多个值赋予优先级非常有用,并且如果缺少该配置,则安全地回退到给定的默认值.这是一个小功能,但我知道,只要我的应用程序升级到PHP 7,我就会使用它.
Yog*_*cha 12
PHP 有一个运算符“...”(三个点),称为 Splat 运算符。它用于在函数中传递任意数量的参数,这种类型的函数称为可变函数。让我们举个例子来使用“...”(三个点)。
示例 1:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
echo calculateNumbers(10, 20, 30, 40, 50);
//Output 150
?>
Run Code Online (Sandbox Code Playgroud)
当使用 "..." 时,calculateNumbers() 函数的每个参数都作为数组传递给 $params。
有许多不同的方法可以使用“...”运算符。下面举几个例子:
示例 2:
<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
$total = $no1 + $no2 + $no3 + $no4 + $no5;
return $total;
}
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);
//Output 150
?>
Run Code Online (Sandbox Code Playgroud)
示例 3:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);
//Output 220
?>
Run Code Online (Sandbox Code Playgroud)
示例 4:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);
//Output 1650
?>
Run Code Online (Sandbox Code Playgroud)
Joh*_*nde 11
PHP 7添加了对返回类型声明的支持。与参数类型声明类似,返回类型声明指定将从函数返回的值的类型。可用于返回类型声明的类型与用于参数类型声明的类型相同。
严格类型化也会对返回类型声明产生影响。在默认的弱模式下,如果返回的值还不是该类型,则将其强制为正确的类型。在强模式下,返回值必须是正确的类型,否则将引发TypeError。
从PHP 7.1.0开始,可以通过在类型名称前添加问号(?)来将返回值标记为可为空。这表示该函数返回指定的类型或NULL。
<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
Joh*_*nde 10
在 PHP 8.0 中添加
它是NullSafe Operator
,它会null
在您尝试调用函数或从 中获取值时返回null
。Nullsafe 运算符可以链接,并且可以在方法和属性上使用。
$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object
Run Code Online (Sandbox Code Playgroud)
Nullsafe 运算符不适用于数组键:
$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null
$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"
Run Code Online (Sandbox Code Playgroud)
在 PHP8 中它被接受了这个新的操作符,你可以在这里找到文档。?->
它是NullSafe Operator
,null
如果您尝试调用函数或从null
...
例子:
<?php
$obj = null;
$obj = $obj?->attr; //return null
$obj = ?->funct(); // return null
$obj = $objDrive->attr; // Error: Trying to get property 'attr' of non-object
?>
Run Code Online (Sandbox Code Playgroud)
#[attribute_name]
从 PHP 8 开始就可以编写。这是PHP(也包括 Rust 和 C#)中的一个属性。其他语言可能使用注释(Java)或装饰器(Python、Javascript)等名称来实现类似的功能。在 PHP 8 之前,#[whatever]
注释一直到行尾(因为#
在 PHP 中开始注释)。因此,如果一个属性是一行中的最后一个内容,则在 PHP 8 之前的版本中它将被忽略。如果不是一行中的最后一个内容,它将注释掉 PHP 8 之前它后面的内容(从那时起终止它]
) 。
归档时间: |
|
查看次数: |
630164 次 |
最近记录: |