What are magic function?

PHP has some magic methods that you can use in OOP (Object-Oriented Programming). All the magic functions must be identified with a double underscore (__) prefix, and they work as interceptors that run when certain required conditions are met.

CAUTION:

PHP reserves all function names starting with __ (double underscore) as magical. It is recommended not to use function names with __ in PHP unless you want some documented magical functionality.

There are some magical functions in PHP listed below:

a) __construct()
b) __destruct()
c) __call()
d) __callStatic()
e) __get()
f) __set()
g) __isset()
h) __unset()
i) __sleep()
j) __wakeup()
k) __toString()
l) __invoke()
m) __set_state()
n) __clone()

These functions are magical in PHP classes. You cannot use these function names in your classes unless you want magical functionality associated with them.

How to use magic functions?

a) __construct()
Creates a new SimpleXMLElement object. This function returns an object on success and FALSE on failure.

Syntax: void __construct([mixed $args[, $…]])

Example:

php
Copy code
class Image
{
public $height;   // height of the image
public $width;   // width of the image

public function __construct($height, $width)
{
$this->height = $height;   // set the height instance variable
$this->width = $width;     // set the width instance variable
}
}

// Create an object of the Image class
$obj = new Image(100, 200);

b) __destruct()

PHP 5 introduced a destructor concept similar to other Object-Oriented Languages. This method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Syntax: void __destruct()

Example:

php
Copy code
class MyDestructor {
function __construct() {
print “In the constructor\n\n”;
$this->name = “MyDestructor”;
}

function __destruct() {
print “Destroying ” . $this->name . “\n”;
}
}

$new_obj = new MyDestructor();
As with the constructor, the parent destructor will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body. Also, like the constructor, a child class may inherit the parent’s destructor if it does not implement one itself. Destructors will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

c) __call()

It is used when invoking inaccessible methods in an object context.

Syntax: __call(string $name, array $args)

Example:

php
Copy code
class Calling {
private $t = array(‘a’, ‘b’, ‘c’);

public function __call($method, $args) {
print “Method $method called:\n”;
var_dump($args);
return $this->t;
}
}

$v = new Calling();
$a = $v->test(10, 20, 30);
var_dump($a);

 

d) __callStatic()

It is used when invoking inaccessible methods in a static context.

Syntax: __callStatic(string $name, array $args)

Example:

php
Copy code
class CallTest
{
public function __call($name, $args)
{
echo “Calling Object Method Name ‘$name’ ” . implode(‘, ‘, $args). “\n\n”;
}

public static function __callStatic($name, $args)
{
echo “Calling Static Method Name ‘$name’ ” . implode(‘, ‘, $args). “\n\n”;
}
}

$new_obj = new CallTest;
$new_obj->runTest(‘in object context’);

CallTest::runTest(‘in static context’);

 

e) __set(), __get(), __isset(), __unset()

__set() is used when writing data to inaccessible properties.
__get() is used for reading data from inaccessible properties.
__isset() is called by calling isset() or empty() on inaccessible properties.
__unset() is used when unset() is used on inaccessible properties.

Syntax:
__set($name, $value)
__get($name)
__isset($name)
__unset($name)

Example:

php
Copy code
class Test {
public $values = array();

public function __get($name) {
return $this->values[$name];
}

public function __set($name, $value) {
$this->values[$name] = $value;
$this->validate($name);
}

public function validate($name) {
$this->$name = trim($this->$name);
}
}

$t = new Test();

$t->hello = ‘testing’;
$t->values[‘hello’] = ‘boing’;

echo ‘$t->hello == ‘ . $t->hello . ‘<br>’;
echo ‘$t ‘ . (property_exists($t, ‘hello’) ? ‘now has’ : ‘still does not have’) . ‘ a property called “hello”<br>’;

 

f) __sleep(), __wakeup()

One of the special features with saving objects is that when serialize() and unserialize() are called, they will look for a __sleep() and __wakeup() function on the object they are working with, respectively. These functions, which you have to provide yourself if you want them to do anything, allow you to properly keep an object working during its hibernation period (when it is just a string of data).

Syntax:
__sleep(void)
__wakeup(void)

Example:

php
Copy code
class StudentInfo {
private $name = ”;
private $roll = 0;
private $sub = array();

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

public function show()
{
echo $this->name;
}

function __sleep()
{
echo ‘Going to sleep now ..’;
return array(‘name’, ‘roll’, ‘sub’);
}

function __wakeup()
{
echo ‘Waking up now ..’;
}
}

 

g) __toString()

This function returns the string representation of the ReflectionClass object.

Syntax: __toString(void)

Example:

php
Copy code
$myclass = new MyClass(‘Hello’);
echo $myclass->__toString();

 

h) __invoke()

This method is used when the object is called as a function. When you declare it, you specify which arguments it should expect.

Syntax: __invoke()

Example:

php
Copy code
class MyClass
{
public function __invoke($a)
{
var_dump($a);
}
}

$new_obj = new MyClass;
$new_obj(50);
var_dump(is_callable($new_obj));

 

i) __set_state()

This method is called for classes exported by var_export().

Syntax: __set_state(array $prop)

j) __clone()

Before understanding the use of a __clone() method, you should understand what object cloning means.

It means creating a duplicate of an object.

Let’s take an example,

With Variables:
$x = $y;

It means that a new variable $x is created that contains the value of $y. Two variables get created.

With Objects:
$new_obj = $obj;

It doesn’t mean that a new object ($new_obj) gets created. When you execute $new_obj = $obj, the reference of $obj is assigned to $new_obj. It simply means that both the objects point to the same memory space.

If you want to create a duplicate object of an object, you need to use the __clone() method.

Example:

php
Copy code
class MyClass {
private $name;

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

public function getName() {
return $this->name;
}
}

$x = new MyClass();
$x->setName(“Gaurav”);

$y = clone $x;

$y->setName(“Shekhar”);

echo $x->getName() . “\n”;
echo $y->getName() . “\n”;
Output:
Gaurav
Shekhar

I hope this helps you to understand the magic functions in PHP 8. If you have any further questions or need clarification, feel free to ask. Thank you!

Leave a Reply