Magic Methods



In PHP, the magic methods are special methods reserved by PHP that allow you to add various skills to your class . These methods start with two hyphens (__) as standard and can only be used in classes. The table below shows what these methods are and what they are used for.

 

 

 

 

Magic Method                           Explanation
void __construct ( Mixed ... $ args ) The constructive method is commonly used to construct the necessary initial configurations and pass them to value sub-methods of a property.
void __destruct ( Void ) Contrary to constructive, the destructive method goes into effect after using the last object of a class .
Mixed __call ( String $ method , Array $ parameters ) When a method that does not belong to a class is invoked, it is activated.
Mixed
__callStatic ( String  $ method , Array  $ parameters )
It is enabled when a static method that does not belong to a class is called. This method must be specified statically.
Mixed __get ( String $ name ) It is activated when a non- belonging attribute is called .
void __set ( String $ name , Mixed $ value ) A qualifier that does not belong to a class is committed when a value assignment is made.
String __toString ( Void ) When an object is converted to a circuit or echo , it is switched on.
Bool __isset ( String $ name ) When a class does not belong to a class, it is activated by isset () .
void __unset ( String $ name ) It is enabled with the use of unset () on a class that does not belong to a class .
Array __sleep ( Void ) It is enabled with the use of a class, eg serialize () . It puts a sequence of names of the class-specific attributes into a special outputable form with serialize () .
void __wakeup ( Void ) If a class is serialized () , then the serialized private data is re- cycled if it is unserialized ()
Mixed __invoke ( Mixed ... $ args ) If a class belongs to an instance, it is used as a function.
void __clone ( Void ) If a clone belongs to a clone , for example clone , it enters the loop.
Array __debugInfo ( Void ) If a class is used with var_dump () , for example , it goes into effect.

 

 

# Construct


The constructive method is commonly used to construct the necessary initial configurations and pass them to value sub-methods of a property. It also provides the sending of a classname parameter while deriving a class instance. This method is a class instance before the use of all methods and attributes to be set up and first enters once-off operation.

Parameters
Mixed $ Args ... Sequential parameters.
return void
Use of
File: Example.php
<?php class Example
{
    public function __construct($parameter)
    {
        echo $parameter . ' guys!';
    }
}

$example = new Example('Hi');
Hi guys!

Now let's give an example of using Vehicle :: and Automobile :: classes that we created earlier . 

File: Vehicle.php
class Vehicle
{
    protected $color = 'White';

    public function __construct(String $color = NULL)
    {
        if( $color !== NULL )
        {
            $this->color = $color;
        }
    }
 
    public function startEngine(Array $connection)
    {
        return $connection;
    }

    public function setColor(String $color)
    {
        $this->color = $color;
    }

    public function getColor() : String
    {
        return $this->color;
    }
}
File: index.php
<?php 

require 'Vehicle.php';
require 'Automobile.php';

$automobile = new Automobile('Blue'); # Vehicle::__construct() yöntemine parametre gönderiliyor.

echo $automobile->getColor();
Blue

In the above example, notice how we send the parameter when doing class declaration with new. 

 

 

# Destruct


This method, in contrast to the __construct () constructor, is enabled after using the most recently used attribute or method of a class instance. So an example is the last working method. It is usually used to terminate a process that is started with the __construct () constructor after the use of the instance.

Parameters
void
return void
Use of
File: Example.php
<?php class Example
{
    public function __construct($parameter)
    {
        echo $parameter . ' guys!<br>';
    }

    public function __destruct()
    {
        echo 'Goodbye!';
    }
}

$example = new Example('Hi');
Hi guys!
Goodbye!

 

 

# Call & CallStatic


When a method that does not belong to a class is invoked, it is activated. The purpose of such use is to provide a flexible method of use.

Knowledge: It is known as overloading of  methods .
Parameters
String $ method Returns the name of this invoked method if a method that does not belong to the class is called.
Array $ parameters This method invokes a list of the array types of the parameters sent.
return Mixed
Use of
File: Example.php
<?php class Example
{
    public function __construct($parameter)
    {
        echo $parameter . ' guys!<br>';
    }

    public function __call($method, $parameters)
    {
        echo $method . ' ' . $parameters[0] . '<br>';
    }

    public function __destruct()
    {
        echo 'Goodbye!';
    }
}

$example = new Example('Hi');
$example->thank('you!')
Hi guys!
thank you!
Goodbye!

Note that in the code above, __call () is activated when the Example :: thank () method is called .

Now let's give an example of using it over the Vehicle :: class we created earlier . 

File: Vehicle.php
class Vehicle
{
    protected $color = 'White';

    public function __construct(String $color = NULL)
    {
        if( $color !== NULL )
        {
            $this->color = $color;
        }
    }

    public function __call($method, $parameters)
    {
        throw Exception('Invalid object call!');
    }
 
    public function startEngine(Array $connection)
    {
        return $connection;
    }

    public function setColor(String $color)
    {
        $this->color = $color;
    }

    public function getColor() : String
    {
        return $this->color;
    }
}
File: index.php
<?php 

require 'Vehicle.php';
require 'Automobile.php';

$automobile = new Automobile('Blue');

echo $automobile->getName();
Invalid object call!
callstatic

This method is called __call () method is not different from the static invocation of the method is to enter. This method must be declared as statically because it enters the circuit with a static call.

File: Example.php
<?php class Example
{
    public function __construct($parameter)
    {
        echo $parameter . ' guys!<br>';
    }

    public static function __callStatic($method, $parameters)
    {
        echo $method . ' ' . $parameters[0] . '<br>';
    }
}

Example::thank('you!');
thank you! 

 

 

# Get


This method is like the __call () method. However, when a property is called instead of a method, it is activated.

Information: Known as overloading of  attributes  .
Parameters
String $ name Your name is called.
return Mixed
Use of
File: Example.php
<?php class Example
{
    public function __get($property)
    {
        echo $property . '<br>';
    }
}

$example = new Example;
echo $example->thankYou;
thankyou

Now let's give an example of using it over the Vehicle :: class we created earlier . 

File: Vehicle.php
class Vehicle
{
    protected $color = 'White';

    public function __construct(String $color = NULL)
    {
        if( $color !== NULL )
        {
            $this->color = $color;
        }
    }

    public function __call($method, $parameters)
    {
        throw Exception('Invalid object call!');
    }

    public function __get($property)
    {
        throw Exception('Invalid property call!');
    }
 
    public function startEngine(Array $connection)
    {
        return $connection;
    }

    public function setColor(String $color)
    {
        $this->color = $color;
    }

    public function getColor() : String
    {
        return $this->color;
    }
}
File: index.php
<?php 

require 'Vehicle.php';
require 'Automobile.php';

$automobile = new Automobile('Blue');

echo $automobile->getName;
Invalid property call!

 

 

# Set


The use of this method is triggered when you try to assign an attribute that does not belong to the class that triggers the __get () method.

Information: Known as overloading of  attributes  .
Parameters
String $ name Your name is called.
Mixed $ Value Your value is worth it.
return Mixed
Use of
File: Example.php
<?php class Example
{
    public function __get($property)
    {
        echo $property . '<br>';
    }

    public function __set($property, $value)
    {
        echo $property . ':' . $value;
    }
}

$example = new Example;
$example->thank = 'you';
Thank: you

 

 

# ToString


Enters when a class instance is converted to string or echoed.

Information:  It is known as representing an object as text .
Parameters
void
return String
Use of
File: Example.php
<?php class Example
{
    protected $getName = __CLASS__;

    public function __toString()
    {
        return $this->getName . '<br>';
    }

    public function setName($name)
    {
        $this->getName = $name;

        return $this;
    }
}

$example = new Example;
 
echo $example;

# Bu yöntem $this ile sınıfın kendisini döndürdüğünden sınıfın örneği 
# gibi kabul edilip __toString() yönteminin tetiklenmesine neden olur.
echo $example->setName('New Name');
Example
New Name

 

 

# Isset & Unset


This method is enabled when a non-class attribute is checked with isset () .

Information: Known as overloading of  attributes  .
Parameters
String $ name Your name is called.
return Mixed
Use of
File: Example.php
<?php class Example
{
    public function __isset($property)
    {
        echo 'Undefined property:' . $property;
    }
}

$example = new Example;

if( isset($example->getName) )
{
    # Kodlarınız...
}
Undefined property: getName
unset 

The use of this method is like __isset () . Trigger when a non-unique attribute is checked with unset () instead of  isset ()

File: Example.php
<?php class Example
{
    public function __unset($property)
    {
        echo 'Undefined property:' . $property;
    }
}

$example = new Example;

if( unset($example->getName) )
{
    # Kodlarınız...
}
Undefined property: getName

 

 

# Sleep


It is enabled with the use of a class, eg serialize () . It puts a sequence of names of the class-specific attributes into a special outputable form with serialize () .

Parameters
void
return Array
Use of
<?php class Example
{
    protected $name, $phone;

    public function __construct($name, $phone)
    {
        $this->name  = $name;
        $this->phone = $phone;
    }

    public function __sleep()
    {
        return ['name', 'phone']; # Serileştirilecek nitelik isimleri.
    }
}

$example = new Example('New Name', '1234');

echo serialize($example);
O: 7: "Example": 2: {s: 7: "* name"; s:

 

 

# Wakeup


If a class is serialized () , then the serialized private data is re- cycled if it is unserialized () . The __sleep () method of the class must be used to trigger this method .

Parameters
void
return void
Use of
<?php class Example
{
    protected $name, $phone;

    public function __construct($name, $phone)
    {
        $this->name  = $name;
        $this->phone = $phone;
    }

    public function __sleep()
    {
        return ['name', 'phone'];
    }

    public function __wakeup()
    {
        echo 'Wakeup!<br>';
    }
}

$example = new Example('New Name', '1234');

$data = unserialize(serialize($example));

var_dump($data);
Wakeup!
object (Example) # 2 ( 2 ) {[ "name": protected] => string ( 8 ) "New Name" [ "phone": protected] => string ( 4 ) "1234"}

 

 

# Invoke


If a class belongs to an instance, it is used as a function.

Parameters
Mixed $ Parameters ... For example the parameters sent.
return Mixed
Use of
<?php class Example
{
    public function __invoke(...$parameters)
    {
        foreach( $parameters as $parameter )
        {
            echo $parameter . '<br>';
        } 
    }
}

$example = new Example;

$example('Example', 1, true, NULL, 'Data');
Example
1
true
NULL
Data

 

 

# Clone


If a clone belongs to a clone , for example clone , it enters the loop.

Parameters
void
return void
Use of
<?php class Example
{
    public function __clone()
    {
        echo 'Instance cloned!';
    }
}

$example = new Example;

$clone = clone $example;
Instance cloned!

 

 

# DebugInfo


If a class  is used with var_dump () , for example  , it goes into effect.

Parameters
void
return Array
Use of
<?php class Example
{
    public function __debugInfo()
    {
        return debug_backtrace(2);
    }
}

$example = new Example;

var_dump($example);
object (Example) # 1 ( 2 )
{
    [0] => array ( 3 )
    {
        [ "function"] => "__debugınfo"
        [ "class"]    => "Example"
        [ "type"]      => " -> "
    }
    [1] => array ( 3 )
    {
        [" file "]      => " C: \ xampp \ htdocs \ example.php "
        [" line "]      => 0
        [" function "] => "var_dump "
    }
}