OOP was designed to allow programmers to more easily model their programs upon real world scenarios - programmers literally define things (objects) in their world (program), set a few basic properties, then ask them to do things. Consider an object of type "dog" - there are many dogs in the world, but only one animal "dog". As such, we have a blueprint for dogs, from which all dogs are made. While dogs have different breeds that vary a great deal, at the end of the day they all have four legs, a wet nose, and a dislike of cats and squirrels.
So, we have our dog blueprint, from which we might create a Poodle breed, a Chihuahua breed, and an Alsatian breed. Each of these are also blueprints, but they are based upon the Dog blueprint. From our Poodle breed we can then create a Poodle, which we will call Poppy. Poppy is an actual dog, based upon the Poodle breed, and therefore also based upon the Dog blueprint. We can create other Poodles (or indeed Chihuahuas or Alsatians) simply by creating an instance of that breed.
As all dogs are able to bark, we can add a bark() function to our dog blueprint, which in turn means that the Poodle breed has a bark() function and therefore Poppy can bark() too. We can also define variables inside the dog blueprint such as $Name, $Age, and $Friendliness - again, this becomes available in the Poodle breed, which stems from the dog animal, and therefore also into Poppy. Each object of type Poodle would have its own set of variables - its own $Name, its own $Age, etc.
Because the breeds stem from the Dog blueprint, we can also add functions and variables to breeds individually without having them in the Dog blueprint. For example, Poodles come in three general sizes: standard, miniature, and toy. Last time I checked, you don't get toy Alsatians, and so putting a $Size variable into the Dog blueprint would just create a variable that is not used in one-third of the dogs.
If you're still with me, then you're on the way to fully understanding how object-oriented code works - there is a lot more to it, but we'll be getting there!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Classes >>
Previous chapter: Objects
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.