PHP中的一个句子中的多个vars赋值 [英] Multiple vars assignment in one sentence in PHP

查看:101
本文介绍了PHP中的一个句子中的多个vars赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问这个var赋值定义会带来什么后果?

I am asking what could be the consequences of this var assignment definition:

$component = $id = $class = '';

我的意思是IDE(phpStorm)允许,该代码不返回任何警告,致命警告或其他任何警告,但....除了...以外还有什么?

I mean is allowed by the IDE (phpStorm), the code doesn't return any warnings, fatal or anything else but .... there is any but?

您怎么看?

推荐答案

没关系.

PHP使用写系统上的副本.这意味着在更改时确实会在内存中创建诸如字符串或整数之类的原始类型,并且在您的示例中可能还可以.

PHP uses a copy on write system. It means that with primitive types such as strings or ints are really created in memory on change and will probably be okay in your example.

php

$component = $id = $class = 'foobar';

var_dump($component);
var_dump($id);
var_dump($class);

输出

string 'foobar' (length=6)
string 'foobar' (length=6)
string 'foobar' (length=6)

但是在对对象执行此操作时要小心,对象是通过引用传递的,并且具有不同的行为:

But be careful when you do this with objects, objects are passed by reference and have different behavior:

PHP

class Obj
{
    public $_name;
}

$a = $b = new Obj();
$component = $id = $class = 'foobar';

$b->_name = 'Reynier'; //try to change name of second object only
$id = 'Reynier'; // try to change $id only

var_dump($a);
var_dump($b);

var_dump($component);
var_dump($id);
var_dump($class);

输出

#Both object are changed
object(Obj)[1]
  public '_name' => string 'Reynier' (length=7)
object(Obj)[1]
  public '_name' => string 'Reynier' (length=7)

#only $id was changed
string 'foobar' (length=6)
string 'Reynier' (length=6)
string 'foobar' (length=6)

这篇关于PHP中的一个句子中的多个vars赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆