Menu
Coddy logo textTech

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:

MethodTriggered 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 Mastery

Without __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 icon

Challenge

Easy

Let'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 a Movie class 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 a Movie instance 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:

MethodTriggered 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)

?>
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