Menu
Coddy logo textTech

Classes vs Objects

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 3 of 91.

Classes and objects serve different purposes. A class is a blueprint, while an object is what you build from that blueprint.

Here is an example of a class with declared properties:

<?php
class Dog {
    public $name;
    public $breed;
}

The public keyword means these properties can be accessed from outside the class. We will learn more about public in the Properties lesson.

Now create objects from the Dog class:

$dog1 = new Dog();
$dog2 = new Dog();

Objects can have individual values for their properties:

$dog1->name = "Nicky";
$dog1->breed = "Siberian Husky";

$dog2->name = "Teemon";
$dog2->breed = "Shu'ali";

The -> operator is used to access an object's properties.

Print each object's data:

echo $dog1->name . " is a " . $dog1->breed . "\n";
echo $dog2->name . " is a " . $dog2->breed . "\n";

Output:

Nicky is a Siberian Husky
Teemon is a Shu'ali

Key Difference: The class Dog defines the structure that all dogs share, while objects $dog1 and $dog2 represent specific, individual dogs with unique property values.

challenge icon

Challenge

Easy

Complete the code to create two student objects from the Student class and set their properties.

  • student.php: Contains the Student class (locked)
  • driver.php: Create objects and set their properties

Set the following values:

  • $student1: name is "Alice" with grade "A"
  • $student2: name is "Bob" with grade "B"

Cheat sheet

A class is a blueprint that defines the structure and behavior of objects, while an object is an instance created from that class.

Define a class with properties using the public keyword:

<?php
class Dog {
    public $name;
    public $breed;
}

Create objects from a class using the new keyword:

$dog1 = new Dog();
$dog2 = new Dog();

Access and set object properties using the -> operator:

$dog1->name = "Nicky";
$dog1->breed = "Siberian Husky";

$dog2->name = "Teemon";
$dog2->breed = "Shu'ali";

Access properties to read their values:

echo $dog1->name . " is a " . $dog1->breed;

Try it yourself

<?php
require_once 'student.php';

// TODO: Create two student objects


// TODO: Set properties for student1 (name: "Alice", grade: "A")


// TODO: Set properties for student2 (name: "Bob", grade: "B")


// Print student information
echo $student1->name . " has grade " . $student1->grade . "\n";
echo $student2->name . " has grade " . $student2->grade . "\n";
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming