Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,338 members
- 696,808 forum posts
- 11 blog posts
Tutorials
OO PHP Part 2: Boring OO Principles
Views: 18061
1 Core OO(P) Principles
1.1 Inheritance
Remember these classes from part 1?
I used them to explain the concept of inheritance to you. Class Dog inherits Animal’s properties and methods when an object is instantiated, if it doesn’t re-declare them itself.
Animal could be the base class for other animal classes, like Bird and Cat. Subclasses like these would have a common interface defined by Animal. Confused? Sharing an interface simply means other components of your application can interact with the classes in a similar way. This interaction is defined by the calling routines (methods and method arguments – the name, arguments and return value of a method is also referred to as the method signature).
In this ridiculously simply example, eat is the whole of the interface. Any class extending Animal is guaranteed to have a eat method which takes a single argument, because even if they don’t declare it themselves, Animal defines the default behaviour.
1.2 Polymorphism
Let’s take a look at a possible Bird…
As you can see, Bird isn’t all that different from Dog. They both eat food. However, because they are not the same type of Animal, they behave differently in response to the $food they are being fed. This is referred to as having their own implementations of the interface provided by Animal, or simply: implementations of Animal.
This is at the core of the principle of polymorphism: Different types of objects can be handled in the same way, even though their implementations vary.
1.3 Encapsulation
Encapsulation refers to ‘isolating’ meaningful parts of your application from each other. This involves hiding information (both data and the implementation of a specific behaviour), and breaking your application into meaningful parts. Often encapsulation is used as a synonym for Information Hiding. But this is only half of the story. The other half, breaking your application into meaningful parts, will be covered in the next chapter.
For a practical example of Information Hiding, check out the heuristic “All Properties Should be Private” later in this tutorial.
