CodeBlanks Logo Icon CodeBlanks

Using with file inclusion

PHP course · Intermediate · Lesson 22/115

Move the class to a separate file and use it in another page with include.

Moving the class to its own file

If you want to reuse a class across projects, it's best to move it into its own file: Collection.php. The class definition is then separated from where it's used, keeping code organized.

In this lesson you'll load the class code into a variable, write it to a file with file_put_contents, then include it with require_once and use it. This mirrors creating the class file by hand in a real project.

Safe paths with __DIR__

Writing a relative path when including a file is risky; the path breaks if the script runs from a different directory. The __DIR__ magic constant returns the absolute path of the file's directory.

With __DIR__ . "/Collection.php" the path stays correct no matter where you run from. You write the class with file_put_contents and load it with require_once.

Exercise Write the class to a file and use it with require_once

Build the file path with $classFile = __DIR__ . "/Collection.php";. Write the class code to the file with file_put_contents($classFile, $classCode);. Include it with require_once $classFile;. Then start with $c = new Collection(["apple"]);, chain $c->add("pear")->add("cherry"); and print the count with echo count($c->items);.

Show example solution
Set $classFile = __DIR__ . "/Collection.php";. Write file_put_contents($classFile, $classCode);. Add require_once $classFile;. Start with new Collection(["apple"]), chain $c->add("pear")->add("cherry");.
Example solution:
<?php
// Write the Collection class to a separate file, then load it with require_once here
$classCode = '<?php
class Collection {
    public array $items = [];
    public function __construct(array $initial = []) {
        $this->items = $initial;
    }
    public function add(string $item) {
        $this->items[] = $item;
        return $this;
    }
}';

$classFile = __DIR__ . "/Collection.php";
file_put_contents($classFile, $classCode);
require_once $classFile;

$c = new Collection(["apple"]);
$c->add("pear")->add("cherry");
echo count($c->items);

Test yourself

  1. Best statement to safely include a class file?

    • include
    • include_once
    • require
    • require_once
    Show answer

    require_once — Correct. require_once includes the class file once; it gives a fatal error if missing and prevents duplicate definitions.

  2. Include Collection.php with require_once

    require_once ____;
    Show answer
    require_once __DIR__ . "/Collection.php";
  3. Match the file inclusion concepts

    require_once
    Includes once, fatal if missing
    require
    Includes each time, fatal if missing
    include
    Warns, script continues
    __DIR__
    File's directory

All lessons in Intermediate