Masa Tono Masa Tono - 5 months ago 10
PHP Question

Copying $_POST to a New (Superglobal) Variable

I am still a beginner, and I want to change all of my

$_POST
into
$_POST2
using a global/superglobal variable. Please help.

Answer

If you want to make a copy of $_POST and call it $_POST2, you can. When copying an array, PHP will make a copy rather than a reference. However, if the array contains objects, those objects will be references to the same old object, rather than clones.

If you really need to copy it:

$_POST2 = $_POST;

Another important note is that $_POST is a superglobal, and your "copy" will not be. The only way to access it without a global $_POST2 would be to reference it via the $GLOBALS superglobal.

echo($GLOBALS['_POST2']['my_var']);

This solution, however, smells of an architectural problem. I'm sure there are other, better ways to solve this, perhaps involving Object Oriented Programming concepts.

Comments