Menu
Coddy logo textTech

External Files

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

External files let you organize your classes in separate PHP files and include them into your main program using require_once.

Create a separate PHP file called my_class.php

<?php
class MyClass {
    // class body
}

Include the file into your main file using require_once

<?php
require_once 'my_class.php';

Now you can use the class in your main file

$obj = new MyClass();
echo get_class($obj);

Output:

MyClass

The require_once 'my_class.php'; statement connects the my_class.php file to your program. The filename must include the .php extension and be wrapped in quotes. require_once ensures the file is loaded only once, even if the statement appears multiple times.

challenge icon

Challenge

Medium

You are given PHP files (my_class.php and driver.php). Add the correct require_once statement in the driver.php file to connect the files and use the class from the external file!

Cheat sheet

Use require_once to include external PHP files into your main program:

require_once 'my_class.php';

The filename must include the .php extension and be wrapped in quotes. require_once ensures the file is loaded only once, even if the statement appears multiple times.

Example of using a class from an external file:

<?php
require_once 'my_class.php';

$obj = new MyClass();
echo get_class($obj); // Output: MyClass

Try it yourself

<?php
// TODO: Add the require_once statement to include my_class.php


$testCase = trim(fgets(STDIN));
$obj = new MyClass();
echo "Test completed\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