Add to Favorites

PHP static classes

PHP static classes can be useful for storing a global scope variable that can be used from within functions or other classes without scope conflicts or worrying about defining a variable as global.

For example, in the past you may have simply defined a variable in your php script like so:

$configuration_preference = 'two';

Then in your function calls you may have used global to modify that variable:

function dosomestuff() {
global $configuration_preference;
$configuration_preference = 'three';

However when you start to have classes that start to use the $configuration_preference variable, the scope of that variable can start to get hairy. You may even accidentally create that same variable within a deeper nested include and end up overwriting your value by accident.

Static variables to the rescue!!

You can create a class and define a variable as a static variable, which can then be used from any scope without declaring a variable as global beforehand. This is handy to keep things in check and group together things like configuration parameters, or paths that you will need later in many different classes. It's simple, create a class, define a static variable:

class config_params {
public static $upload_path = 'user_uploads/files/';

Then within your function, you just reference the class:

function dosomestuff() {
return glob(config_params::$upload_path .'*.*');


Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up