复制或不复制PHP中的其他变量? [英] Copy or don't copy extra variables in PHP?

查看:88
本文介绍了复制或不复制PHP中的其他变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 Google Developers PHP性能提示,我发现这不是'建议您额外复制一个变量.

Reading the Google Developers PHP performance tips I saw that it isn't recommended to make an extra copy of a varible.

代替此:

$description = strip_tags($_POST['description']);
echo $description;

它建议这样做:

echo strip_tags($_POST['description']);

原因是可能不必要的内存消耗.

The reason is a possible unnecessary consumption of memory.

但是进行一些搜索时,我看到一些反驳,说PHP实现了写时复制"内存管理.这基本上意味着我们可以为任意多个变量分配一个值,而不必担心实际复制的数据.

But doing some searches I saw some rebuttals saing that PHP implements "copy-on-write" memory management. This basically means that we can assign a value to as many variables as we like without having to worry about the data actually being copied.

所以我想知道在更复杂的情况下,例如在代码的许多地方将使用$_POST$_GET变量的情况,考虑到使用还是不使用额外的变量是更好的做法这些条件:

So I would like to know if in more complex situations, where for example $_POST or $_GET variables will be used in many places of the code, whether it is better practice to use or not use extra variables, considering these criteria:

1)安全

2)维护/可读性

3)性能

编辑1

我将使用以下示例更好地说明问题.

I will use the below example to better ilustrate the question.

这种代码是否更好(考虑以上条件):

Is it better this kind code (Considering the criteria above):

$user = anti_injection($_POST['user']);
$pass = anti_injection($_POST['pass']);

// Continue the code using $user and $pass

还是这个?

$_POST['user'] = anti_injection($_POST['user']);
$_POST['pass'] = anti_injection($_POST['pass']);

// Continue the code using $_POST['user'] and $_POST['pass']

推荐答案

PHP的惰性副本"仅适用于数组.仅当更改数组的一个副本时,数组的数据才会重复,这就是为什么foreach循环可以在原始数组的副本上工作的原因.

PHP's "lazy copy" only applies to arrays. The array's data is only duplicated if one copy of the array is changed, which is why it's okay for the foreach loop to work on a copy of the original array, for instance.

对象通过引用传递,即使未通过&指示这样做也是如此.示例:

Objects are passed by reference, even when not told to do so with &. Example:

$a = new StdClass();
$b = $a;
$b->derp = "foo";
var_dump($a->derp); // "foo"

资源是对特定扩展要使用的资源的引用,因此无法有意义地进行复制.

Resources are references to a resource to be used by a particular extension, so they can't meaningfully be copied.

所有其他内容都直接复制.

Everything else is copied directly.

无论如何都应避免不必要的变量.例如,代替:

Unnecessary variables should be avoided anyway. For instance, instead of:

$step1 = 123;
$step2 = $step1 * 4;
$step3 = $step2 + 99;
$step4 = $step3 / 3;
echo $step4;

您可以这样写:

echo (123*4+99)/3;

(或者在本例中为echo 197;)

重点是,非专有变量确实会造成混乱,并可能与您在其他地方定义的变量发生冲突.

The point is, unnexessary variables do create clutter and could potentially conflict with a variable you defined elsewhere.

这篇关于复制或不复制PHP中的其他变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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