CodeBlanks Logo Icon CodeBlanks

Project: Utility library

PHP course · Intermediate · Lesson 19/115

Overview of the 5-lesson utility library: reusable structures with class + include.

Project: Utility library

In this 5-lesson project you'll build a reusable utility library. Each lesson adds one piece, and by the final lesson you'll have a working module.

You'll use what you learned in previous groups: classes, constructors and inheritance. Throughout the project you'll design a Collection class: a structure that stores items in an array, has add and find methods, and can be moved to a separate file and included from other pages.

Project roadmap

The project has five lessons. In the second lesson you'll write the class skeleton and the constructor. In the third you'll add add, remove and find methods. In the fourth you'll move the class to a separate file and include it with require_once. In the final lesson you'll combine all parts and complete the working library.

Exercise Define the Collection class

Write the first piece of this project. Define a class named Collection. Add a public array $items = []; property (empty array default). Then create an instance with $c = new Collection(); and print the item count with echo count($c->items);.

Show example solution
Declare the class with class Collection { ... }, add public array $items = [];. Create an instance with new Collection() and print with echo count($c->items);.
Example solution:
<?php
// Define the Collection class and create an empty instance
class Collection {
    public array $items = [];
}

$c = new Collection();
echo count($c->items);

Test yourself

  1. Why is a library class useful?

    • It bundles data and methods in one unit, easing reuse.
    • It slows code down but improves readability.
    • It is only used for database operations.
    • It makes variable definitions unnecessary.
    Show answer

    It bundles data and methods in one unit, easing reuse. — Correct. A class groups related data and methods in one unit, so you can reuse the code in other projects.

  2. Complete the class declaration

    class ____ {
        public array $items = [];
    }
    Show answer
    class Collection {
        public array $items = [];
    }
  3. Match the project concepts

    Collection
    Structure holding items
    Constructor
    Sets up internal state
    Library
    Reusable module
    Method
    Behavior of a class

All lessons in Intermediate