0
I am developing a project and it works with many files and these files are called via require_once()
.
It is hard work to declare each variable created as a global variable in view of the number of files, obviously not all, but the ones that need to declare need attention, because sometimes I end up forgetting and the error of indefinite variable.
I did a test here and got it with the native PHP function get_defined_vars()
, transform all variables into global variables automatically. The code for this is as follows::
foreach (get_defined_vars() as $name_var => $content_var)
{
$GLOBALS[$name_var] = $content_var;
}
It facilitated the process, because now I can have a return of all system variables with a simple var_dump($GLOBALS)
.
But even this working I consider a gambiarra, because this method can generate problems with the variables since the variables of the same name will be replaced.
I am also concerned about the information overload since the way I executed the function all variables, without exception, will be a global, so even the variables that no longer have usefulness in processing will be transformed into global.
Is there any way to improve this process by doing the same thing I want to do only in a more viable way?
I thought of using a class that would be in charge of this process, where I could set the variables that I wish to have global access to. In this way I centralize all conversions.
Why exactly do you need global variables? I, in particular, have never seen an application that really needed to do something like this, so I could better explain what it’s doing to make sure whether or not it’s an XY problem?
– Woss
Let’s say I have home.view.php, for this view I have a home.controller.php, within this controller I have variables declared (not by functions or classes) that have values that I could use in home.view, but if I try to use any of these variables, it will give error of indefinite variable. Hence my need to obtain these variables in a practical way. In fact the problem may be XY, for this reason I went to the site, to see the correct way to do it using good practices, and not a gambiarra as it was (already I changed to class).
– ivan veloso