PHP: How not to pollute the global scope
An emerging trend in JavaScript is to wrap entire programs in a single object to prevent conflicts with other scripts. The same can be done with PHP, something I haven’t seen done very often.
If you ever want to combine frameworks you may discover that they use similar names for some variables and functions. This can lead to unexpected output and security holes. If you’re planning on writing a framework of your own, consider wrapping it in an object.
In PHP5 it’s possible to pass objects by reference which means you can send an instance of a class to another class. This way you can nest classes and access the parent.
core.php:
class core { public $var = 'This is a global variable.'; const CONST_VAR = 'This is a constant.'; // This function is executed when core is initialized. function __construct() { include('classes/foo.php'); $this->foo = new foo($this); } // All the main functions go here. }
foo.php:
class foo { private $core; function __construct($core) { // Reference to the core object. $this->core = $core; } function hello_world() { echo $this->core->var; } }
In this example “core” is the site’s main object containing global variables and functions. When we create an instance of class “foo”, we send a reference to the core object (“$this”) as a parameter. On a regular page the classes, variables and function can be accessed like this:
page.php
include('classes/core.php'); $core = new core(); echo $core->var; // output: This is a global variable. echo core::CONST_VAR; // output: This is a constant. $core->foo->hello_world(); // output: This is a global variable.
This way there is only one variable in the global scope: $core. Another advantage is that all variables declared in core are global and accessible throughout the whole program.
Filed under Programming