Recap - Custom Collection
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 50 of 91.
Challenge
EasyLet's build a Collection class that brings together all the magic methods you've learned in this chapter. Your collection will act as a flexible data container that feels natural to use — storing items by key, checking if they exist, finding items dynamically, and creating independent copies.
You'll organize your code across two files:
Collection.php— Create aCollectionclass that stores items in a private array. Your collection should support these magic methods working together:__construct()— Accepts an optional array of initial items (default to empty array)__get($key)— Returns the item at the given key, ornullif it doesn't exist__set($key, $value)— Stores the value at the given key__isset($key)— Returns whether the key exists in the collection__unset($key)— Removes the item at the given key__call($method, $args)— Handles dynamic finder methods. When a method starting withfindByis called (likefindByRoleorfindByStatus), extract the field name (lowercase the part after "findBy"), search through all items, and return the key of the first item where that field matches the first argument. Returnnullif no match is found. For any other method, return"Unknown method: [method]"__toString()— Returns"Collection([count] items)"where count is the number of items__clone()— When cloned, the items array should be a fresh copy (not a reference to the original)
main.php— Include the Collection file. You'll receive three inputs: a key name, a role value, and a search role. Build a collection of users and demonstrate all the magic methods:- Create a new
Collection - Add a user with the input key, storing an array with
"name"set to the key and"role"set to the input role value - Add another user with key
"bob", storing["name" => "Bob", "role" => "editor"] - Print whether the input key exists using
isset()— output"exists"or"missing" - Print the result of calling the dynamic
findByRole()method with the search role as the argument (this should return the key of the matching user, or nothing if null) - Print the collection using
echo(triggers__toString) - Clone the collection, then unset the input key from the clone
- Print whether the input key exists in the original collection — output
"exists"or"missing"(should still exist since clone is independent)
- Create a new
Each output should be on its own line. The dynamic finder assumes each item in your collection is an associative array with fields like "name" and "role".
Try it yourself
<?php
require_once 'Collection.php';
// Read inputs
$keyName = trim(fgets(STDIN));
$roleValue = trim(fgets(STDIN));
$searchRole = trim(fgets(STDIN));
// TODO: Create a new Collection
// TODO: Add a user with the input key, storing array with "name" => key and "role" => roleValue
// TODO: Add another user with key "bob", storing ["name" => "Bob", "role" => "editor"]
// TODO: Print whether the input key exists using isset() - output "exists" or "missing"
// TODO: Print the result of calling findByRole() with searchRole as argument
// TODO: Print the collection using echo (triggers __toString)
// TODO: Clone the collection, then unset the input key from the clone
// TODO: Print whether input key exists in the ORIGINAL collection - "exists" or "missing"
?>All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern