PHP Object Manipulation with Magic Methods

Nihar Ranjan Das
4 min readMay 14, 2023

--

By Admin, Published on May 14th, 2023 | 10 mins, 924 words

In PHP, magic methods are special methods that allow you to define how an object behaves in certain situations. These methods are automatically called by PHP under specific circumstances, such as when you access undefined or inaccessible properties, call undefined methods, or perform certain operations on objects. Magic methods are identified by their reserved method names, prefixed with double underscores.

Some special instructions for magic methods:

  1. All methods names starting with __ are reserved by PHP
  2. All magic methods except __construct(), __destruct(), and __clone(), need to be declared as public, otherwise, an E_WARNING will be thrown. Before to PHP 8.0.0, no diagnostic was emitted for the magic methods __sleep(), __wakeup(), __serialize(), __unserialize(), and __set_state().
  3. __construct() and __destruct() should not have a return type; otherwise a fatal error will be thrown.

Here are some commonly used magic methods in PHP:

  1. __construct(): This magic method is called automatically when an object is created from a class. It is used to initialize object properties and perform setup operations.
  2. __destruct(): It is called automatically when an object is no longer referenced or explicitly destroyed. It can be used to perform cleanup operations or release resources.
  3. __get($name): This method is called when you attempt to access a non-existent or inaccessible property of an object. It receives the name of the property being accessed as a parameter and allows you to define custom logic to handle such access.
  4. __set($name, $value): It is called when you attempt to assign a value to a non-existent or inaccessible property of an object. It receives the name of the property being set and the value being assigned as parameters, allowing you to define custom logic for handling such assignments.
  5. __isset($name): This method is called when you use the `isset()` or `empty()` functions on an object property. It receives the name of the property as a parameter and allows you to define custom logic to determine if the property is set.
  6. __unset($name): It is called when you use the unset() function on an object property. It receives the name of the property as a parameter and allows you to define custom logic to unset or remove the property.
  7. __call($name, $arguments): This method is called when you try to call a non-existent or inaccessible method of an object. It receives the name of the method being called and an array of arguments passed to the method. It allows you to define custom logic to handle such method calls.
  8. __callStatic($name, $arguments): This method is called when you try to call a non-existent or inaccessible static method of an object. This is the only difference between __callStatic() and __call().
  9. __toString(): It is called when you try to treat an object as a string, such as when using `echo` or `print` on an object. It allows you to define custom logic to convert the object to a string representation.

These are the most important magic methods in PHP. Magic methods provide a way to dynamically handle certain operations and can be useful for implementing behaviors like method overloading, property access control, and object serialization.

Here’s an example that utilizes several magic methods in PHP:

class Book { 
private string $title;
private string $author;
private array $pages = [];
public static int $age = 15;

public function __construct(string $title, string $author)
{
$this->title = $title; $this->author = $author;
}
public function __get(string $name): string|array|null
{
if (isset($this->{$name})) {
return $this->{$name};
}
return null;
}

public function __set(string $name, string|array $value): void
{
if (isset($this->{$name})) {
if (is_array($value)) {
$this->pages = $value;
} else {
$this->{$name} = $value;
}
}
}

public function __isset(string $name): bool
{
return isset($this->{$name});
}

public function __unset(string $name): void
{
if (isset($this->{$name})) {
if (is_array($this->{$name})) {
$this->pages = [];
}
else {
$this->{$name} = '';
}
}
}

public function __call(string $name, array $arguments): void
{
if ($name === 'addPage') {
if (isset($arguments[0])) {
$this->pages[] = $arguments[0];
}
}
}

public static function __callStatic(string $name, array $arguments): void
{
if ($name === 'setAge') {
if (isset($arguments[0])) {
self::$age = $arguments[0];
}
}
}

public function __toString(): string
{
return "Book: {$this->title} by {$this->author}";
}
}

// Usage:
$book = new Book('The Great Gatsby', 'F. Scott Fitzgerald');
echo $book; // Output: Book: The Great Gatsby by F. Scott Fitzgerald

$book->addPage('Chapter 1');
$book->addPage('Chapter 2');
echo $book->pageCount; // Output: 2

$book->pages = ['Introduction', 'Chapter 1', 'Chapter 2'];
echo $book->pageCount; // Output: 3

if (isset($book->author)) {
echo "Author is set.";
}

unset($book->pages);
echo $book->pageCount; // Output: 0

Book::setAge(32);
echo Book::$age; // Output: 32

In this example, the Book class represents a book with properties like title, author, age, and pages. The magic methods are used as follows:

  • __construct(): Initializes the Book object with a title and an author.
  • __get($name): Handles access to the pageCount property, returning the number of pages.
  • __set($name, $value): Handles assignment to the pages property, allowing only an array of pages to be assigned.
  • __isset($name): Handles the check for the existence of the author property.
  • __unset($name): Handles the removal of all pages when the pages property is unset.
  • __call($name, $arguments): Handles the dynamic addition of pages using the addPage() method.
  • __callStatic($name, $arguments): Handles the dynamic age setting using the setAge() method.
  • __toString(): Converts the Book object into a string representation.

The usage section demonstrates how to create a Book object, add pages, access the page count, check for the existence of the author property, remove pages, and convert the object to a string.

Originally published at https://nihardaily.com on May 14, 2023.

--

--