THE MAGICAL DESTRUCT METHOD

php logoUsually the constructor is invoked automatically during the creation of an object, it is used to initialize the properties with the values passed in input, in general it initializes properties and services used by the class, by services I mean other objects that the class may need. Similarly when an object no longer needs to be in memory or because the script terminates or because there are no more references to that object PHP calls the method __destruct (). The method __destruct () is not a real destructor but it serves to do some operations before the object is actually destroyed, for example closing an open file, a connection to a database etc.

Desctruct
Copy to Clipboard

THE MAGIC METHODS SLEEP, WAKEUP, SERIALIZE AND UNSERIALIZE

When we serialize an object we might want to prevent some properties from being serialized, and when we deserialize we might want to be able to do some operations. For example, if we don’t want to serialize a property, we use the magic method  __sleep ();

image one

WE CHANGE THE CODE OF THE FILE MANAGER CLASS

Let’s take the code of the FileManager class using the SplFileObject class in order to make the code more OOP and less procedural.

image three

This is $testfile2 var_dump () .

image two

THE MAGIC METHODS SERIALIZE AND UNSERIALIZE

As seen from var_dump() the fileObj property is not initialized, not all objects are serializable , so we cannot use the read() method to read the file. The problem is solved with the magic __wakeup() method. The magic methods __sleep() and __wakeup() are used in serialization and de-serialization, respectively. Since PHP 7.4 they have been replaced with __serialize() and __unserialize().

Copy to Clipboard

THE MAGIC METHODS GET AND SET

We cannot access private or global scope properties, the __get magic method controls access to non-existent or inaccessible properties. __set assigns a value to a property, private or protected.

Copy to Clipboard

THE MAGICAL METHOD CALL

As we know the classes we write must not be too large but compact and inserted in a much wider context. If a class doesn’t have all the features in it, somewhere it needs to have it to accomplish its task. One of the methods we have studied is inheritance. If we enter the __call() method it means that I have the method exists within the Course class but it is not accessible, or it does not exist in the Course class but exists in the EmailService class. The magic __call() method can be useful for delegating the invocation of a method of one class from another class.

Copy to Clipboard

THE MAGICAL CALLSTATIC METHOD

It is very similar to the __call() method except in this case __callStatic() is inherent in static methods. __callStatic() intercepts the non-existent method in the code below.

callStatic_code
var_dump
Copy to Clipboard

DEEPENING

In PHP, there are several “magic methods” that allow you to perform specific operations on objects. These magic methods always begin with a double underscore (__) and are used to define special behaviors in certain situations. Below I explain the magic methods you requested: __serialize(), __unserialize(), __sleep(), __wakeup(), __call(), and __callStatic().

1. __serialize() and __unserialize().

These two magic methods are used for serializing and deserializing objects. As of PHP 7.4, it is preferable to use __serialize() and __unserialize() instead of __sleep() and __wakeup() for more robust and modern serialization handling.

– __serialize()

This method is called when serializing an object with serialize(). Its purpose is to return an array-friendly representation of the object.

class MyClass {
      private $data;

      public function __construct($data) {
          $this->data = $data;
      }

      public function __serialize(): array {
            return [‘data‘ => $this->data];
      }
}

$obj = new MyClass(“example data“);
$serialized = serialize($obj);

– __unserialize()

It is called when an object is deserialized with unserialize(). Takes as input an array, typically returned by __serialize().

class MyClass {
      private $data;

      public function __unserialize(array $data): void {
          $this->data = $data[‘data’];
      }
}

$unserialized = unserialize($serialized);

2. __sleep() and __wakeup().

These magic methods are used in serialization and deserialization of objects in earlier versions of PHP (before PHP 7.4).

– __sleep()

This method is called when serializing an object with serialize(). It is used to return an array containing the names of the properties you want to serialize. It also allows you to do cleanup, such as closing database connections before serialization.

class MyClass {
  private $data;

     public function __sleep() {
           return [‘data’]; // Solo la proprietà ‘data’ verrà serializzata
      }
}

– __wakeup()

It is called during deserialization with unserialize(). It is used, for example, to reestablish database connections or regenerate resources.

class MyClass {
      private $data;

      public function __wakeup() {
      // Ristabilire connessioni o eseguire altre operazioni necessarie
     }
}

3. __call()

This method is called when a method is invoked that does not exist or is inaccessible (e.g., private or protected) on an object. It accepts two parameters: the name of the method called and an array of arguments passed.

class MyClass {
        public function __call($name, $arguments) {
           echoIl metodo ‘$name’ non esiste. Parametri: ” . implode(‘, ‘, $arguments);
        }
}

$obj = new MyClass();
$obj->nonExistingMethod(‘arg1’, ‘arg2’);

4. __callStatic()

Similar to __call(), but applies to static methods. This method is called when a static method is invoked that does not exist or is not accessible.

class MyClass {
        public static function __callStatic($name, $arguments) {
            echoIl metodo statico ‘$name’ non esiste. Parametri: “ . implode(‘, ‘, $arguments);
        }
}

MyClass::nonExistingStaticMethod(‘arg1’, ‘arg2’);

Summary

-__serialize() and __unserialize(): for custom serialization and deserialization (as of PHP 7.4).

-__sleep() and __wakeup(): earlier versions of serialization and deserialization.

-__call(): handles calls to non-existent or inaccessible methods on objects.

-__callStatic(): handles calls to non-existing or inaccessible static methods.

These methods are powerful tools for controlling the behavior of objects and their properties in specific situations.

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB