Object Oriented PHP
March 20, 2015
OOP Basics
Die drei Kernideen:
- Encapsulation (Kapselung)
- Inheritance (Vererbung)
- Polymorphism (Polymorphie)
Klassen und Objekte
Eine Klasse ist ein Blueprint, ein Objekt ist die Instanz.
code
class Product {
public $name;
public $price;
public function getInfo() {
return $this->name . " - " . $this->price;
}
}
$p = new Product();
$p->name = "Book";
$p->price = 9.99;
echo $p->getInfo();
Sichtbarkeit (Scope)
public: von ueberallprotected: Klasse + Childprivate: nur in der Klasse selbst
code
class User {
public $name;
protected $role;
private $passwordHash;
}
$this
$this zeigt auf die aktuelle Instanz.
code
public function getName() {
return $this->name;
}
Konstruktor
code
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
}
$p = new Product("Book", 9.99);