---
# System prepended metadata

title: 'Lecture 2: PHP Object-Oriented Programming (OOP) - Preparing for Laravel'

---

# Lecture 2: PHP Object-Oriented Programming (OOP) - Preparing for Laravel

**Duration:** 2-3 Hours
**Trainer:** Fadi Ramzi Mohammed
**Level:** Beginner to Intermediate
**Tools Required:** VS Code + XAMPP (PHP 8.2 or higher)

---

## Objectives

By the end of this lecture, trainees will:

- Understand the fundamentals of Object-Oriented Programming (OOP) in PHP
- Learn how OOP is used in modern PHP frameworks like Laravel
- Practice writing classes, properties, methods, inheritance, and access modifiers
- Prepare foundational OOP skills needed for Laravel controllers, models, and services

---

## ✅ What is OOP?

OOP (Object-Oriented Programming) is a programming paradigm based on the concept of "objects" which contain data (properties) and behavior (methods).

### Real-life Analogy:

Think of a **Car**:

- Properties: color, brand, model
- Behaviors: start(), accelerate(), brake()

You can create multiple car **objects** based on the **Car class**.

---

## 🔸 1. Creating a Class and Object

### Syntax:

```php
<?php
class Car {
  public $brand;
  public $color;

  public function start() {
    echo "The car is starting.";
  }
}

$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->color = "Red";

echo $myCar->brand;  // Output: Toyota
$myCar->start();     // Output: The car is starting.
?>
```

### Explanation:

- `class Car {}` defines a blueprint
- `$myCar = new Car();` creates an object
- `->` is used to access object properties/methods

---

## 🔸 2. Constructors (\_\_construct)

### Syntax:

```php
<?php
class User {
  public $name;

  public function __construct($name) {
    $this->name = $name;
  }

  public function greet() {
    echo "Hello, $this->name";
  }
}

$user = new User("Fadi");
$user->greet(); // Hello, Fadi
?>
```

### Explanation:

- `__construct()` runs automatically when an object is created
- `$this` refers to the current object

---

## 🔸 3. Access Modifiers: public, private, protected

### Example:

```php
<?php
class Account {
  public $owner;
  private $balance;

  public function __construct($owner, $balance) {
    $this->owner = $owner;
    $this->balance = $balance;
  }

  public function getBalance() {
    return $this->balance;
  }
}

$acc = new Account("Ali", 1000);
echo $acc->getBalance(); // 1000
?>
```

### Explanation:

- `public`: accessible anywhere
- `private`: only accessible inside the same class
- `protected`: accessible in the class and child classes

---

## 🔸 4. Inheritance

### Syntax:

```php
<?php
class Person {
  public $name;
  public function speak() {
    echo "$this->name is speaking.";
  }
}

class Employee extends Person {
  public $position;

  public function work() {
    echo "$this->name is working as a $this->position.";
  }
}

$emp = new Employee();
$emp->name = "Sara";
$emp->position = "Developer";
$emp->speak();
$emp->work();
?>
```

### Explanation:

- `extends` allows class to inherit properties/methods from another
- Useful to reduce code duplication

---

## 🔸 5. Encapsulation (Getters and Setters)

### Example:

```php
<?php
class BankAccount {
  private $balance = 0;

  public function deposit($amount) {
    if ($amount > 0) {
      $this->balance += $amount;
    }
  }

  public function getBalance() {
    return $this->balance;
  }
}

$account = new BankAccount();
$account->deposit(500);
echo $account->getBalance(); // 500
?>
```

### Explanation:

- Encapsulation hides internal data
- Methods are used to safely access and modify properties

---

## 🔸 6. Class Constants and Static Methods

### Example:

```php
<?php
class AppConfig {
  const VERSION = "1.0";

  public static function info() {
    echo "App version is " . self::VERSION;
  }
}

AppConfig::info();
?>
```

### Explanation:

- `const` for constant values shared across all objects
- `static` method can be called without creating an object
- `self::` is used to access static properties/methods

---

## 🧠 Practice Exercises

### Task 1:

Create a class `Product` with:

- Properties: `name`, `price`
- Constructor to set both
- Method `printInfo()` to print product details

### Task 2:

Create two classes:

- `User`: with name and login() method
- `Admin`: extends User, adds `accessLevel` and override `login()` to show different message

### Task 3:

Create a `MathTool` class:

- `static` method `add($a, $b)` and `multiply($a, $b)`
- Call them without creating object

---

## 🔸 7. Laravel 12: Fresh Project Setup, Composer, and OOP Connection

### ✅ Why We Use Composer

Composer is the **dependency manager** for PHP. Laravel depends on Composer to:
- Download its framework and packages
- Autoload PHP classes automatically (PSR-4)
- Manage package versions and updates

#### 🔧 Installing Composer (on Windows)
1. Go to https://getcomposer.org
2. Download **Composer-Setup.exe**
3. During installation, provide the PHP path:  
   `C:\xampp\php\php.exe`
4. After installation, open CMD and verify:
   ```bash
   composer -V

### Create the project
```
composer create-project laravel/laravel my-platform-app "^12.0"
cd my-platform-app
php artisan serve
```

### Laravel Routing, Controllers & OOP in Action
What is Routing?
Routing defines what should happen when a user visits a URL.

Example:
```php
// routes/web.php
Route::get('/', function () {
    return view('welcome');
});

```
This returns a Blade view when the user accesses /.


#### 👉 Creating a Controller
`php artisan make:controller ExpertController`

Now edit app/Http/Controllers/HomeController.php:

```php
// app/Http/Controllers/ExpertController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExpertController extends Controller {
    public function profile() {
        return view('experts.profile');
    }
}


```

Update routes/web.php:
```php
use App\Http\Controllers\ExpertController;

Route::get('/expert/profile', [ExpertController::class, 'profile']);

```

###  OOP in Laravel: Models and Services
Create a model:

```
php artisan make:model Product

```

php artisan make:model Expert -m

This creates app/Models/Expert.php, representing the experts table.

```php
// app/Models/Expert.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Expert extends Model {
    protected $fillable = ['name', 'bio', 'category', 'price'];
}

```


## Resources

- PHP Manual OOP: [https://www.php.net/manual/en/language.oop5.php](https://www.php.net/manual/en/language.oop5.php)
- Laravel OOP Basics: [https://laravel.com/docs/12.x](https://laravel.com/docs/12.x)
- Laracasts (OOP for Laravel): [https://laracasts.com](https://laracasts.com)

---

Prepared by: Fadi Ramzi
Date: 30-06-2025

