Primer On Globals, PHP, Classes. or OOP.

This is a post about PHP classes written for class/OOP (Object-Oriented Programming) n00bs. If that’s you, feel free to stick around. This post also is based on the assumption that you’ve become accustomed to using php functions and WordPress template tags (just a fancy name for a php function).

Update: This is not an exhaustive tutorial on OOP and some have pointed out that using a global to store an object is anti-OOP. I’ll eventually write a post on the “right way” and post it here (for now, definitely check out Ronald’s recommendation). That being said, this method will work, and you’ll be better off starting with this than not starting at all.

My intention with this post is to give an extremely simplistic introduction to PHP classes, and hopefully take some of the mystery out of using them. The big idea is that we’ll be:

  1. Initiating a global variable.
  2. Creating a PHP class.
  3. Adding a property to that class.
  4. Adding a method  to that class.
  5. Giving that method some functionality.
  6. Initiating the class & adding it to our global.
  7. In another function, method, or file, grabbing that global out of the air, and using it’s bundled up functionality.

1) Initiating a global variable.

We’ll actually use this variable in a bit. For now, let’s just tell it to exist. This needs to be unique just like naming functions. Using a prefix is recommended. From now on the term ‘global variable’ is shortened to ‘global’.

This is different than a normal variable in that it is available in all scopes (inside and outside of functions, classes, templates, etc). If you’ve ever seen or used WordPress’ global $post; before, that is a reference to the current loop’s post object. Globals are grabbed out of the global space by either one of two ways.

  1. global $bundle_of_functionality;: You would then use $bundle_of_functionality from that point forward. The global keyword just plucks it out of global space the first time.
  2. $GLOBALS[‘bundle_of_functionality’]: Using the global this way, you’re not actually plucking the global out of global space, but just referencing it from the global space array. Trippy. You would continue to use $GLOBALS[‘bundle_of_functionality’] each time you needed it.
<?php
// initiate a global variable
global $bundle_of_functionality;

Caution: If you make any changes to a global variable, it will be permanent. For that reason, many times you’ll see a global variable sent to a local variable like: $local_variable = $bundle_of_functionality. Then, if you change $local_variable, $bundle_of_functionality remains intact for the next time you need to use it.

2) Creating a PHP class.

This also needs to be unique and should be prefixed.

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

}

3) Adding a property to that class.

A property is just a fancy name for a variable that’s available throughout the class object. To use it, you’ll use the $this keyword followed by an arrow, followed by the property name (without the $). So.. $this-&gt;words_to_say.

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

  /**
   * A public class property
   * 
   * (variables that float out here are called
   *   properties & are accessible everywhere 
   *   inside the class)
   */
  public $words_to_say = 'do stuff';

}

4) Adding a method  to that class.

A method is just a fancy name for a “function” inside a class. That’s made even more confusing by the fact that it’s created the same way, using the term “function”: function my_method(){}. You use a class method the same way you use a class property, call  the $this keyword followed by an arrow, followed by the method: $this-&gt;do_stuff().

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

  /**
   * A public class property
   * 
   * (variables that float out here are called
   *   properties & are accessible everywhere 
   *   inside the class)
   */
  public $words_to_say = 'do stuff';

  /**
   * A public method
   * 
   * (functions in classes are called methods..
   *   how pretentious)
   */
  public function do_stuff() {

  }

}

5) Giving that method some functionality.

In our case, when called, it will simply grab our $words_to_say property and echo it out.

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

  /**
   * A public class property
   * 
   * (variables that float out here are called
   *   properties & are accessible everywhere 
   *   inside the class)
   */
  public $words_to_say = 'do stuff';

  /**
   * A public method
   * 
   * (functions in classes are called methods..
   *   how pretentious)
   */
  public function do_stuff() {
    // '$this' is a magical keyword to 
    // reference our class object
    echo $this->words_to_say;
    // later we'll put $this into $bundle_of_functionality
  }

}

6) Initiating the class & adding it to our global

You initiate the class by using the keyword ‘new’ in front of the class name. The parenthesis at the end of the class name are optional unless you’re passing data into the class (out of scope for this post). Just initiating this particular class won’t have any effect, so we want to throw the entire class’ functionality into that global to be used anywhere. That’s really the power of classes, and the bundled up package of functionality and data is called an object.

<?php
// initiate a global variable
global $bundle_of_functionality;

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

  /**
   * A public class property
   * 
   * (variables that float out here are called
   *   properties & are accessible everywhere 
   *   inside the class)
   */
  public $words_to_say = 'do stuff';

  /**
   * A public method
   * 
   * (functions in classes are called methods..
   *   how pretentious)
   */
  public function do_stuff() {
    // '$this' is a magical keyword to 
    // reference our class object
    echo $this->words_to_say;
    // later we'll put $this into $bundle_of_functionality
  }

}
// throw the class into our global variable..
// we now have an "object" stashed in a variable.
$bundle_of_functionality = new Class_That_Does_Stuff();

7) In another function, method, or file, grabbing that global out of the air, and using it’s bundled up functionality.

Let’s grab that object and make it ‘do stuff’ (get it?). To use this method now, you’ll replace the $this keyword with our variable: $bundle_of_functionality-&gt;mymethod().

/**
 * Some other file
 */

// grab the global
global $bundle_of_functionality;

// and use the public methods
// echos 'do stuff'
$bundle_of_functionality->do_stuff();

Ok, all together now!

<?php
// initiate a global variable
global $bundle_of_functionality;

/**
 * A PHP Class that does things
 */
class Class_That_Does_Stuff {

  /**
   * A public class property
   * 
   * (variables that float out here are called
   *   properties & are accessible everywhere 
   *   inside the class)
   */
  public $words_to_say = 'do stuff';

  /**
   * A public method
   * 
   * (functions in classes are called methods..
   *   how pretentious)
   */
  public function do_stuff() {
    // '$this' is a magical keyword to 
    // reference our class object
    echo $this->words_to_say;
    // later we'll put $this into $bundle_of_functionality
  }

}
// throw the class into our global variable..
// we now have an "object" stashed in a variable.
$bundle_of_functionality = new Class_That_Does_Stuff();


...


/**
 * Some other file
 */

// grab the global
global $bundle_of_functionality;

// and use the public methods
// echos 'do stuff'
$bundle_of_functionality->do_stuff();

 

Let me know if this made any lightbulbs go off or if you have any questions. Also, take some time to read through these other excellent (better?) resources.

Resources:

  1. Ben Lobaugh explains OOP philosophically: https://webdevstudios.com/2015/12/08/unexpected-practical-applications-programming-skills
  2. http://wpshout.com/concepts-oo-php-wordpress-development/
  3. http://blog.teamtreehouse.com/getting-started-with-oop-php5
  4. http://codular.com/introducing-php-classes
  5. http://www.phpclasses.org/blog/post/178-Why-is-it-better-to-develop-in-PHP-with-classes-OOP.html
  6. http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
  7. These videos are awesome too. http://www.meetup.com/Front-Range-PHP-User-Group/messages/boards/thread/36043752 (thanks @ryancduff)
  8. Skip the global, use a singleton: http://wp.tutsplus.com/tutorials/creative-coding/design-patterns-in-wordpress-the-singleton-pattern (thanks Ronald Huereca)
  9. No, DON’T use a singleton: http://dsgnwrks.pro/development-principles/gary-jones-recommended-resources-on-avoiding-singletons (thanks Gary Jones)

5 Comments on “Primer On Globals, PHP, Classes. or OOP.

    • Thanks Ronald. I added that link to the resources. I need to do some learning myself on Singletons, cuz that sounds slick.

  1. Pingback: PHP globals and classes for new programmers | Post Status

Comment

Fast, secure WordPress hosting is provided by WP Engine.
%d bloggers like this: