Your Favorite Color: Classes

  1. Your Favorite Color
  2. Simple form

Once you start getting into more complex code, you’ll have a lot of variables and functions. You might imagine have one variable for the current time, and then in another separate part of your page having a variable for the time that an event starts, and elsewhere a variable storing the amount of time left until some event happens. It’s not unlikely that with all that complexity you’ll end up calling different values by the same name, creating hard-to-find bugs as one value gets overwritten by unrelated values.

To keep your variables and functions in one place, and to keep them from interfering with each other, you’ll use classes. A class in PHP is a collection of functions and variables with a common purpose; when used in a class, a function is called a “method” and a variable is called a “property”. Classes have methods and properties. That’s part of what makes them useful.

Another part of what makes them useful is that they can be re-used very easily. When you use a class, you create an instance of that class. That instance is called an “object” and you can create as many objects out of that class as you need.

You can imagine a class of animals called dogs. Dogs have teeth and fur, and they growl and hunt. Teeth and fur are properties, and growl and hunt are methods. And you might have a particular instance of a dog called “fido”.

Further, you might have an overall class called Animal that Dogs inherit from, as do Cats and Buffalo. Some things all animals can do, other things are limited to a specific class of Animal. Another of the advantages of classes is that you can extend them and share common functionality—methods and properties—among classes that share a parent class.

You’ll see all of this in the next two examples.

  1. Your Favorite Color
  2. Simple form