Classes & Objects There are two main programming paradigms: Procedural Object-Oriented Up to now, everything we have done has been procedural.
Procedural Programming A list of instructions to carry out step-by-step Programs execute from the top down, line by line Programs can rely heavily on functions & other procedures (conditionals, loops)
You should have a good understanding of: variables operators conditionals (if statements) loops functions
Object-Oriented Programming OOP - all computations are based on objects Objects are instances of Classes For example, a dog named Rover is an object of the dog class A class is a blueprint or template for making objects
Example Person Class class Person { private $first; private $last; private $age; } Class with 3 properties (variables) private scope of property – only visible in this class
Class Scope 3 identifiers for class properties (variables) and methods (functions) public – visible outside the class protected - visible to any inherited class private – visible only inside that class
Magic Constructor Method class Person { private $first; private $last; private $age; public function __construct($first, $last, $age) { $this->first = $first; $this->last = $last; $this->age = $age; }
new Object $obj = new Person(); Automatically calls magic constructor method public function __construct() (notice double underscore)
public function __construct($first, $last, $age) { $this->first = $first; $this->last = $last; $this->age = $age; } Special variable $this refers to current object Object operator -> points to class properties & methods Class property references ->age do not use $
Class with New Object class Person { private $first; private $last; private $age; public function __construct($first, $last, $age) { $this->first = $first; $this->last = $last; $this->age = $age; } $obj = new Person($first, $last, $age);
Inheritance Classes may inherit from other classes class Mammal { protected $vertebra; } class Tiger extends Mammal { protected $stripes; public function __construct($vertebra, $stripes) { Mammal::__construct($vertebra); $this -> stripes = $stripes;
:: Scope Resolution Operator Use the scope resolution operator :: to access properties and methods outside the class. public function __construct($vertebra, $stripes) { Mammal::__construct($vertebra);