Menu
Coddy logo textTech

Introduction to OOP

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

Object-Oriented Programming (OOP) organizes code around objects that contain data (properties) and functions (methods).

Create a file called car.php with a class

<?php
class Car {
    // empty class body
}

Create another file called driver.php to use the class

<?php
require_once 'car.php';

Create an object from the Car class using the new keyword

$myCar = new Car();

Check the class of your object

echo get_class($myCar);

Output:

Car

This confirms you've successfully created an object from your Car class. In OOP, a class is like a blueprint, and an object is what you build from that blueprint. The new keyword creates a new instance of the class.

challenge icon

Challenge

Medium

In this challenge, you'll use a Car class defined in car.php and create an object from it in driver.php.

You need to update driver.php:

  1. Create an object from the Car class using the new keyword and store it in $myCar

The driver file will print the class name to verify your implementation.

Cheat sheet

Object-Oriented Programming (OOP) organizes code around objects that contain data (properties) and functions (methods).

Define a class:

<?php
class Car {
    // empty class body
}

Include a class file in another file:

<?php
require_once 'car.php';

Create an object from a class using the new keyword:

$myCar = new Car();

Check the class of an object:

echo get_class($myCar); // Output: Car

A class is like a blueprint, and an object is an instance created from that blueprint.

Try it yourself

<?php
require_once 'car.php';

// TODO: Create an object from the Car class
$myCar = ?;

// Print the class of $myCar
echo get_class($myCar) . "\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