← Back to PHP Course | Chapter 8: OOP | Lesson 2 of 14

PHP Classes & Objects

Creating a Class

You define a class with the class keyword followed by a name and a body containing properties (variables) and methods (functions) that belong to it, like class Car { public $color; function drive() {} }.

Example: Creating a Class

php
<?php
class Car {
    public $color;
    function drive() {
        echo "Driving!";
    }
}
?>

Instantiating Objects

You create an object from a class using the new keyword, such as $myCar = new Car();, which allocates a fresh instance with its own independent copy of the class's properties.

Example: Instantiating Objects

php
<?php
class Car {
    public $color;
}
$myCar = new Car();
var_dump($myCar);
?>

Accessing and Modifying Properties

Object properties are accessed with the -> (arrow) operator, so $myCar->color = red; sets that specific object's color without affecting any other Car object you might have created.

Example: Accessing and Modifying Properties

php
<?php
class Car {
    public $color;
}
$myCar = new Car();
$myCar->color = 'red';
echo $myCar->color;
?>

Writing Class Methods

You can create multiple independent objects from the same class, and changes to one object's properties never affect another object's properties, since each holds its own separate state in memory.

Example: Writing Class Methods

php
<?php
class Car {
    public $color;
}
$car1 = new Car();
$car1->color = "red";
$car2 = new Car();
$car2->color = "blue";
echo $car1->color . " " . $car2->color;
?>

Using the $this Keyword

Methods defined inside a class can read and modify that object's own properties directly by name, without needing to pass them in as parameters, since they execute in the context of that specific object.

Example: Using the $this Keyword

php
<?php
class Car {
    public $color = "red";
    function showColor() {
        echo $this->color;
    }
}
$car = new Car();
$car->showColor();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.