Reading the Google Developers PHP performance tips I saw that it isn’t recommended to make an extra copy of a varible.
Instead of this:
$description = strip_tags($_POST['description']);
echo $description;
It recommends this:
echo strip_tags($_POST['description']);
The reason is a possible unnecessary consumption of memory.
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.
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) Security
2) Maintenance / Readability
3) Performance
EDIT 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
Or this?
$_POST['user'] = anti_injection($_POST['user']);
$_POST['pass'] = anti_injection($_POST['pass']);
// Continue the code using $_POST['user'] and $_POST['pass']
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
foreachloop 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: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:
You could just write:
(or, in this case, just
echo 197;)The point is, unnexessary variables do create clutter and could potentially conflict with a variable you defined elsewhere.