I understand any user input needs to be sanitized.
Any framework I’ve made does this. Naturally any “applicable” variables/names in any URL query or form input are pre-allocated specifically.
Simple albeit foolish question. Is there any reason you should have a class with a constructor like the following
function __construct( $get, $post, $server )
and initiated as
new TheClass( $_GET, $_POST, $_SERVER );
as opposed to simply grabbing them in the constructor itself as they are defined? Pardon if it’s obvious I was pretty good at all this just a bit rusty now. Seeing what you guys think.
Advertisement
Answer
One good idea in programming is to think of functions as units that only depend on inputs and only affect on outputs (and maybe the object they’re called on). This is also one of the main principles of functional programming.
The most basic tenet of functional programming is that, as much as possible, computation should be pure, in the sense that the only effect of execution should be to produce a result: it should be free from side effects such as I/O, assignments to mutable variables, redirecting pointers, etc. For example, whereas an imperative sorting function might take a list of numbers and rearrange its pointers to put the list in order, a pure sorting function would take the original list and return a new list containing the same numbers in sorted order.
From Software Foundations book.
Reading and writing global variables in different parts and units would make the code buggy, hard to read/understand, hard to follow, etc. It would be a good practice to work with them in only one part of code, and not any functions, methods, etc. From this point of view this is really good to not read $_GET
, $_POST
, etc. inside __construct
or any other methods directly and pass them from somewhere known for the programmer and people who are working on the project. This gets more critic when it’s about writing, i.e., in $_SESSION
variable. Imagine the $_SESSION
value contains some unwanted data and you need to figure out which part of the code is responsible for the issue. If there are many part of the code that change the $_SESSION
variable, the debug processes is gonna be very hard.
So in my opinion This is very good to not use global variables as possible.