Currently I am re-vamping some code that I currently have written something like this:
<?php
global $foo;
$foo = "foo";
class foo{
function bar(){
global $foo;
return $foo."bar";
}
}
$class = new foo();
echo foo->bar();
//returns 'foobar';
?>
This works, just fine. My question is, is this the correct way to include the variables? Some of my class files have upwards of 20 global variables, that have to be redefined as global in every method that they are used in.
Avoid global variables when you can. I won’t bother repeating here why, as there are many answers on SO explaining why it’s considered a bad practice (example).
Instead, pass the variables you need inside your class to your constructor, like: