PHP Object-Oriented Programming Beginner's Guide
Class vs Object
- Class is generic, whereas Object is specific
- Class defines properties/functions of an Object
- Object is an instance of a Class
- You can instantiate an object, but not a Class
PHP Class
Class House {
public $postCode = “560121”;
public function ringBell() {
echo “Ding Dang Dong”;
}
}
$house = new House();
Visibility
Inheritance
class Shape {
public function name() {
echo "I am a shape";
}
}
class Circle extends Shape {
}
$circle = new Circle();
$circle->name(); // I am a shape
Polymorphism
interface Shape {
public function name();
}
class Circle implements Shape {
public function name() {
echo "I am a circle";
}
}
class Triangle implements Shape {
public function name() {
echo "I am a triangle";
}
}
function test(Shape $shape) {
$shape->name();
}
test(new Circle()); // I am a circle
test(new Triangle()); // I am a triangle
Encapsulation
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName($name) {
return $this->name;
}
}
$robin = new Person();
$robin->setName('Robin');
$robin->getName();
Abstraction
class TV {
private $isOn = false;
public function turnOn() {
$this->isOn = true;
}
public function turnOff() {
$this->isOn = false;
}
}
$tv = new TV();
$tv->turnOn();
$tv->turnOff();
Interface vs Abstract class
Interface
interface Vehicle {
public function startEngine();
}
class Car implements Vehicle {
public function startEngine() {
echo "Engine Started";
}
}
Abstract class
abstract class Vehicle {
abstract public function startEngine();
public function stopEngine() {
echo "Engine stoped";
}
}
class Car extends Vehicle {
public function startEngine() {
echo "Engine Started";
}
}