PHP“&”运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2209934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:31:21  来源:igfitidea点击:

PHP "&" operator

php

提问by Bob Rivers

I'm not a PHP programmer (but know other languages), and I'm trying to understand a web page that was done in PHP (5.1.6) in order to do some changes.

我不是 PHP 程序员(但知道其他语言),我试图理解用 PHP (5.1.6) 完成的网页,以便进行一些更改。

The page has the following code (simplified):

该页面具有以下代码(简化):

$db_hosts = array();
$sql = 'SELECT h.hostid, h.host FROM hosts h ';

$db_items = DBselect($sql);

while($db_item = DBfetch($db_items)){
    $name = $db_item['host'];
    $db_host = &$db_hosts[$db_item['hostid']];
}

I'm trying to understand the last line, $db_host = &$db_hosts[$db_item['hostid']];.

我试图理解最后一行,$db_host = &$db_hosts[$db_item['hostid']];.

It seems to be creating a new variable, $db_host, and putting something inside it, but I don't understand &$db_hosts.

它似乎正在创建一个新变量,$db_host并在其中放入一些东西,但我不明白&$db_hosts

I'm in doubt because as far as I know, $db_hostsis an empty array.

我有疑问,因为据我所知,$db_hosts是一个空数组。

I found thisand this, but I'm not quite sure, because in these links, the operator is "=&", and in the code, the operator is attached to the variable "= &$db_hosts" (it has an space between = and &).

我找到了thisthis,但我不太确定,因为在这些链接中,运算符是“=&”,而在代码中,运算符附加到变量“= &$db_hosts”(它有一个空格= 和 & 之间)。

Since I tried to modify it and didn't get success, I thought that it was better to ask for help...

既然我尝试修改了没有成功,我觉得还是求助一下比较好……

回答by LiraNuna

Those are references, and they are similar to "pointers" in C or C++.

这些是引用,它们类似于 C 或 C++ 中的“指针”。

More information is in the PHP manual.

更多信息在PHP 手册中

In this case, since $db_hostsis empty, the construct $db_hosts[$db_item['hostid']]will create a new array with an empty item on the index of $db_item['hostid']and return the item's reference, making $db_hostact as an 'alias' for whatever $db_hosts[$db_item['hostid']]is currently.

在这种情况下,由于$db_hosts为空,该构造$db_hosts[$db_item['hostid']]将创建一个新数组,该数组的索引为空项目$db_item['hostid']并返回该项目的引用,从而$db_host充当$db_hosts[$db_item['hostid']]当前任何内容的“别名” 。

回答by IMSoP

&is used variously in PHP to denote References (see this manual section), but it is misleading to think of it as being an operator in its own right. This is why some people prefer to write $foo =& $barrather than $foo = &$bar- it means the same thing, but emphasises that the "reference-y-ness" is a property of the assignment, not of the variables.

&在 PHP 中以多种方式用于表示引用(请参阅本手册部分),但将其视为本身的运算符是一种误导。这就是为什么有些人更喜欢写$foo =& $bar而不是$foo = &$bar- 这意味着同样的事情,但强调“reference-y-ness”是赋值的属性,而不是变量的属性。

In some programming languages, such as C or C++, you can "get a reference to" a particular variable; the resulting value can be passed around as a distinct entity, and then "de-referenced" to find out where it points. This is notwhat PHP references are.

在某些编程语言中,例如 C 或 C++,您可以“获得对特定变量的引用”;结果值可以作为一个不同的实体传递,然后“取消引用”以找出它指向的位置。这不是PHP 引用。

Instead, allPHP variables are actually references to an internal type called a zval. You cannot directly manipulate zvals in PHP, and nor can you make extra layers of indirection - every variable is a reference to a zval, and that's it. (See caveat: objects below.)

相反,所有PHP 变量实际上都是对称为 a 的内部类型的引用zval。您不能zval在 PHP 中直接操作s,也不能创建额外的间接层——每个变量都是对 a 的引用zval,仅此而已。(请参阅警告:下面的对象。)

What an assignment-by-reference ($foo =& $bar), a pass-by-reference (function foo(&$bar) { ... }), or a return-by-reference (return &$foo) do is tell PHP that you want two variables to point at the same zval. Note that you are not pointing one variable "at" another - they are both equally "real", and calling unset()on either will leave the other completely untouched.

引用赋值 ( $foo =& $bar)、引用传递 ( function foo(&$bar) { ... }) 或引用返回 ( return &$foo) 的作用是告诉 PHP 您希望两个变量指向同一个zval. 请注意,您并没有将一个变量“指向”另一个变量——它们都同样“真实”,调用unset()其中一个将使另一个完全保持不变。

Caveat: objects

警告:对象

It is often misleadingly said that since PHP5 objects are "always passed by reference". The truth is that they have an extralayer of indirection, where the zvalis itself a pointer to a particular object. This gives us three different things we can refer to: the variable, the zvalit points at, and the objectthat that points at:

由于 PHP5 对象“总是通过引用传递”,因此经常被误导。事实是,它们有一个额外的间接层,其中zval本身就是一个指向特定对象的指针。这给了我们三个可以引用的不同的东西:变量zval它指向的对象和它指向的对象

// Create an object, and point three variables at it in different ways:
$foo = new stdClass;
$bar_by_value = $foo;
$bar_by_ref =& $foo;

// Change the object: updates the object shared by all three variables
$foo->value = 42;
// Change the value (zval) of $foo: will update $bar_by_ref, 
//   but $bar_by_value still points at the original object
$foo = 42; 
// Change the variable itself: will never affect $bar_by_value or $bar_by_ref
unset($foo);

回答by dev.meghraj

Question:

问题

What does "&" mean here in PHP?

PHP中的“&”是什么意思?

PHP "&" operator

PHP“&”运算符

Makes life more easier once we get used to it..(check example below carefully)

一旦我们习惯了它会让生活更轻松..(仔细检查下面的例子)

&usually checks bits that are set in both $a and $b are set.

&通常检查在 $a 和 $b 中设置的位是否设置。

have you even noticed how these calls works?

你有没有注意到这些调用是如何工作的?

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

So behind all above is game of bitwise operator and bits.

因此,在以上所有内容的背后是按位运算符和位的游戏。

One usefull case of these is easy configurations like give below, so a single integer field can store thousands of combos for you.

其中一个有用的例子是简单的配置,例如下面给出的,因此单个整数字段可以为您存储数千个组合。

Most people have already read the docs but didn't reliase the real world use case of these bitwise operators.

大多数人已经阅读了文档,但没有依赖这些按位运算符的实际用例。

Example That's can be very useful everyday php life

示例 这对 php 日常生活非常有用

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

回答by JAL

Assigning that variable as a reference makes it so that if later on $db_host is changed, the corresponding entry in the $db_hosts array will change as well, and vice versa.

将该变量分配为引用使得如果稍后 $db_host 发生更改,则 $db_hosts 数组中的相应条目也将更改,反之亦然。

I've seen a fair bit of rather pointless use of references in PHP, cargo cult style. Perhaps this one is needed, perhaps not - you'd have to look at the rest of the program.

我在 PHP 中看到了相当无意义的引用,货物崇拜风格。也许需要这个,也许不需要——您必须查看程序的其余部分。

回答by dusoft

&is used as a reference. See what references are in http://php.net/manual/en/language.references.php:

&用作参考。查看http://php.net/manual/en/language.references.php 中的引用 :

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on.

PHP 中的引用是一种通过不同名称访问相同变量内容的方法。它们不像 C 指针;例如,您不能使用它们执行指针运算,它们不是实际的内存地址,等等。

回答by Josh

The & is used to get a reference to a variable. It's similar to references in other languages like C++, with some significant differences. See the PHP Manual's section on references.

& 用于获取对变量的引用。它类似于 C++ 等其他语言中的引用,但有一些显着差异。请参阅PHP 手册的参考部分

回答by krishna Prasad

Here is simple example to explain the meaning of PHP &operator:

下面是一个简单的例子来解释 PHP&运算符的含义:

<?php

$x = "Hello";

$y = &$x;
echo "Value of x : " . $x . "\n";
echo "Value of y : " . $y . "\n";

$y = "Hi"; // Since $y is alias or reference of the variable $x, so value of $x will also be changed, see below:

echo "Value of x : " . $x . "\n";
echo "Value of y : " . $y . "\n";

Output of the above code is as follow:

上述代码的输出如下:

Value of x : Hello
Value of y : Hello
Value of x : Hi
Value of y : Hi

From the above example, it is clear that it is reference of the variable.

从上面的例子可以看出,它是变量的引用。

From official documentation: What References Are

来自官方文档:参考文献是什么

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

PHP 中的引用是一种通过不同名称访问相同变量内容的方法。它们不像 C 指针;例如,您不能使用它们执行指针运算,它们不是实际的内存地址,等等。有关更多信息,请参阅引用不是什么。相反,它们是符号表别名。注意在PHP中,变量名和变量内容是不同的,所以相同的内容可以有不同的名字。最接近的类比是 Unix 文件名和文件——变量名是目录条目,而变量内容是文件本身。引用可以比作​​ Unix 文件系统中的硬链接。