Object-Oriented Programming
## Learning Objectives
- Understand classes and objects
- Master encapsulation and visibility
- Work with inheritance
- Learn interfaces and traits
- Understand namespacing
## Classes and Objects
### Class Definition
```php
name = $name;
$this->age = $age;
}
// Methods
public function greet(): string {
return "Hello, my name is " . $this->name;
}
}
?>
```
### Creating Objects
```php
greet(); // Hello, my name is Alice
echo $person1->name; // Alice
?>
```
## Properties
### Property Declaration
```php
```
### Typed Properties (PHP 7.4+)
```php
```
## Visibility (Access Modifiers)
### Public
```php
name = "Alice"; // OK
?>
```
### Protected
```php
ssn = $ssn; // OK - within same class hierarchy
}
}
$person = new Person();
$person->ssn = "123-45-6789"; // Error!
?>
```
### Private
```php
secret; // OK - within same class
}
}
$person = new Person();
echo $person->secret; // Error!
echo $person->reveal(); // "hidden"
?>
```
## Methods
### Method Definition
```php
```
### $this Keyword
```php
name = $name; // $this refers to the current object
}
public function getName(): string {
return $this->name;
}
}
?>
```
## Constructors and Destructors
### Constructor
```php
name = $name;
$this->age = $age;
}
}
$person = new Person("Alice", 25);
$default = new Person("Bob"); // age defaults to 0
?>
```
### Constructor Property Promotion (PHP 8)
```php
name; // Alice
echo $person->age; // 25
?>
```
### Destructor
```php
connection = connect($host);
}
public function __destruct() {
close($this->connection); // Cleanup when object is destroyed
}
}
?>
```
## Inheritance
### extends Keyword
```php
name = $name;
}
public function speak(): string {
return "...";
}
}
class Dog extends Animal {
public function speak(): string {
return "Woof!";
}
public function fetch(): string {
return "$this->name fetches the ball";
}
}
$dog = new Dog("Buddy");
echo $dog->speak(); // Woof!
echo $dog->fetch(); // Buddy fetches the ball
?>
```
### parent Keyword
```php
name = $name;
$this->age = $age;
}
}
class Employee extends Person {
private string $position;
public function __construct(
string $name,
int $age,
string $position
) {
parent::__construct($name, $age); // Call parent constructor
$this->position = $position;
}
}
?>
```
## Abstract Classes
### Definition
```php
area();
}
}
?>
```
### Implementation
```php
radius = $radius;
}
public function area(): float {
return pi() * $this->radius ** 2;
}
public function perimeter(): float {
return 2 * pi() * $this->radius;
}
}
class Rectangle extends Shape {
private float $width;
private float $height;
public function __construct(float $width, float $height) {
$this->width = $width;
$this->height = $height;
}
public function area(): float {
return $this->width * $this->height;
}
public function perimeter(): float {
return 2 * ($this->width + $this->height);
}
}
?>
```
## Interfaces
### Interface Definition
```php
```
### Interface Implementation
```php
balance += $amount;
return true;
}
public function refund(float $amount): bool {
if ($amount > $this->balance) {
return false;
}
$this->balance -= $amount;
return true;
}
public function getBalance(): float {
return $this->balance;
}
}
class PayPalGateway implements PaymentGateway {
// ... implements all methods
}
?>
```
### Multiple Interfaces
```php
```
### Interface Inheritance
```php
```
## Traits
### Basic Trait
```php
logs[] = date("Y-m-d H:i:s") . ": $message";
}
public function getLogs(): array {
return $this->logs;
}
}
?>
```
### Using Traits
```php
name = $name;
$this->log("User created: $name");
}
}
$user = new User("Alice");
echo $user->getLogs()[0]; // 2024-01-01 12:00:00: User created: Alice
?>
```
### Multiple Traits
```php
createdAt = time();
}
}
trait Validateable {
public function validate(): bool {
// validation logic
return true;
}
}
class Entity {
use Timestamp, Validateable;
}
?>
```
### Conflict Resolution
```php
hello(); // B
echo $obj->hi(); // A
?>
```
### Trait Property Override
```php
createdAt = time();
}
}
class Entity {
use Timestamped;
public function __construct() {
$this->setTimestamp();
}
}
?>
```
## Static Members
### Static Properties
```php
```
### Static Methods
```php
```
### Late Static Binding
```php
```
## Constants
### Class Constants
```php
```
### Interface Constants
```php
```
## Type Checking
### instanceof
```php
```
### Class Name Resolution
```php
```
## Object Comparison
```php
```
## Namespaces
### Declaration
```php
```
### Using Namespaces
```php
```
### use Statement
```php
```
### Aliases
```php
```
### Global Namespace
```php
input); // Global trim()
}
}
?>
```
## Autoloading
### spl_autoload_register
```php
```
### PSR-4 with Composer
```json
{
"autoload": {
"psr-4": {
"App\\": "src/",
"Tests\\": "tests/"
}
}
}
```
## Summary
- Classes: `class Name { }`
- Objects: `new ClassName()`
- Visibility: `public`, `protected`, `private`
- Constructor: `__construct()`
- Inheritance: `class Child extends Parent`
- Abstract: `abstract class` and `abstract method`
- Interfaces: `interface` and `implements`
- Traits: `trait Name` and `use TraitName`
- Static: `static $property` and `static method()`
- Constants: `const NAME = value`
- Namespaces: `namespace App\Models;`
- Autoloading: `spl_autoload_register()` or Composer
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →