Magic Methods Introduction
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 44 of 91.
Magic methods are special methods in PHP that start with double underscores (__) and are automatically called by PHP in response to certain events or actions. You've already used two of them: __construct() and __destruct().
These methods let you hook into PHP's internal behavior and customize how your objects respond to common operations.
For example, what happens when you try to print an object? Or access a property that doesn't exist? Magic methods give you control over these situations.
Here's a quick overview of the most commonly used magic methods:
| Method | Triggered When |
|---|---|
__construct() | Object is created |
__destruct() | Object is destroyed |
__toString() | Object is used as a string |
__get() | Accessing undefined property |
__set() | Setting undefined property |
__call() | Calling undefined method |
__clone() | Object is cloned |
<?php
class Book {
public function __construct(
private string $title
) {}
public function __toString(): string {
return "Book: " . $this->title;
}
}
$book = new Book("PHP Mastery");
echo $book;
Output:
Book: PHP MasteryWithout __toString(), trying to echo an object would cause an error. The magic method intercepts this action and returns a string representation instead. In the upcoming lessons, we'll explore each magic method in detail.
Challenge
EasyLet's build a movie catalog system that introduces you to magic methods. You'll create a Movie class that uses __construct() to initialize movie data and __toString() to provide a clean string representation when the object is printed.
You'll organize your code across two files:
Movie.php— Create aMovieclass that represents films in your catalog. Use constructor promotion to define private properties for$title(string),$director(string), and$year(integer). Implement the__toString()magic method to return a formatted string:"[title] ([year]) - Directed by [director]". This allows your movie objects to be echoed directly without calling a separate method.main.php— Include the Movie file. You'll receive three inputs: a movie title, a director name, and a release year. Create aMovieinstance using these values (convert the year to an integer). Then simply echo the movie object directly — the__toString()method will automatically be called to produce the output.
The magic of __toString() is that PHP automatically calls it whenever your object is used in a string context. Instead of writing echo $movie->getInfo();, you can simply write echo $movie; and PHP handles the conversion for you. This makes your objects more intuitive to work with.
Cheat sheet
Magic methods are special methods in PHP that start with double underscores (__) and are automatically called by PHP in response to certain events or actions.
Common magic methods:
| Method | Triggered When |
|---|---|
__construct() | Object is created |
__destruct() | Object is destroyed |
__toString() | Object is used as a string |
__get() | Accessing undefined property |
__set() | Setting undefined property |
__call() | Calling undefined method |
__clone() | Object is cloned |
The __toString() method returns a string representation of an object:
<?php
class Book {
public function __construct(
private string $title
) {}
public function __toString(): string {
return "Book: " . $this->title;
}
}
$book = new Book("PHP Mastery");
echo $book; // Output: Book: PHP Mastery
Without __toString(), trying to echo an object would cause an error. The magic method intercepts this action and allows the object to be used in a string context.
Try it yourself
<?php
require_once 'Movie.php';
// Read input
$title = trim(fgets(STDIN));
$director = trim(fgets(STDIN));
$year = intval(fgets(STDIN));
// TODO: Create a Movie instance using the input values
// TODO: Echo the movie object directly (the __toString() method will be called automatically)
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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