OOP: Classes & Objects

🐘 PHP Lesson 8 Intermediate

PHP has a complete object-oriented programming model. In this lesson, we will look at classes, visibility modifiers, constructors, and instantiating objects.

1 Property Visibility & Constructors

PHP classes group properties and methods. Properties can use visibility modifiers to control access: `public`, `protected`, or `private`. Constructors are defined using the special method name **`__construct()`**.

2 Classes Code

Let's run a program declaring classes and instantiating objects:

PHP — Classes & Objects ▶ Run Code
<?php
class Car {
    public $model; // Public access
    private $year;  // Private access

    // Constructor
    public function __construct(string $model, int $year) {
        $this->model = $model; // '$this' references current instance (no '$' before property name)
        $this->year = $year;
    }

    public function showDetails() {
        echo "Model: " . $this->model . ", Year: " . $this->year . "\n";
    }
}

// Instantiate object using 'new'
$myCar = new Car("Ford Mustang", 2022);
$myCar->showDetails();
?>
3 Code Challenge
Challenge: Write a class named `Student` with properties `name` and `gpa`. Add a constructor to initialize them, and a method called `display` to output their details.