PHP Object-Oriented Programming Basics
Why OOP? • Modularity • Operation isolation • Better code reuse • Flexibility • Maintainability Classes • Define the characteristics and behaviors for a thing in the system • Nouns • e.g. a car has a make and model and can accelerate and turn Class Example class Car { public $make; // Characteristic public $model; public function accelerate() { // Behavior // … } public function turn() { // … }} UML: Class Diagram Objects • An instance of a thing (or class). • e.g. a particular car, such as John’s Camry. Methods • Behaviors specific to a thing • Usually actions that objects may perform • Also called operations • Verbs Members • Characteristics of a thing • Also called: • Properties • Variables • Attributes Instance vs Static • Instance methods always operate on the current object (PHP’s default) • Static methods are shared by all instances of a class • And cannot use $this Visibility • Public: Visible to everything • Private: Visible only within the class • Protected: Visible within the class and it’s subclasses OOP Principles • Inheritance: child classes inherit behaviors and characteristics from parent classes • Abstraction: models may become more specific or generic as needed OOP Principles • Encapsulation: the devil may be in the details, but they’re not important • Polymorphism: Behaviors may change from generation to generation Polymorphic Methods • Virtual Methods: methods that can change in child classes (PHP’s default) • Final Methods: methods that cannot be overridden • Abstract Methods: methods that must be verridden Relationships • Dependency: Objects work briefly with each other • Association: More prolonged interaction • Aggregation: One object references another • Composition: One class contains another UML: Diagram Advice • It’s OK to mix objects and classes (and other artifacts!) • Diagramming, not modeling • Use diagrams for communication • Don’t diagram what you don’t have to Why Patterns? • Repeatable solutions to common problems • Solutions that are already proven effective • Common language for communicating designs.
Download PHP Object-Oriented Programming Basics.Pdf