What are magic methods and how to use them in PHP ?
Last Updated :
15 Mar, 2022
PHP magic methods are special methods that are called automatically when certain conditions are met. There are several magic methods in PHP. Every magic method follows certain rules -
- Every magic method starts with a double underscore ( __ ).
- They are predefined and neither can be created nor removed.
- Magic methods have reserved names and their name should not be used for other purposes.
- Magic methods are automatically called when certain criteria are met.
Method Names | Return types | Condition of calling |
__construct() | NaN |
This method gets called automatically every time the object of a particular class is created.
The function of this magic method is the same as the constructor in any OOP language.
|
__destruct() | NaN |
As the name suggests this method is called when the object is destroyed and no longer in use.
Generally at the end of the program and end of the function.
|
__call($name,$parameter) | Not mandatory | This method executes when a method is called which is not defined yet. |
__toString() | String |
This method is called when we need to convert the object into a string.
For example: echo $obj;
The $obj->__toString(); will be called magically.
|
__get($name) | NaN | This method is called when an inaccessible variable or non-existing variable is used. |
__set($name , $value) | NaN | This method is called when an inaccessible variable or non-existing variable is written. |
__debugInfo() | array | This magic method is executed when an object is used inside var_dump() for debugging purposes. |
The following are code snippets and examples to understand magic methods better.
__construct() Method: In the below example, the MagicMethod class has a magic method __construct() and it is called every time when a new object of MagicMethod class is created.
PHP
<?php
class MagicMethod {
function __construct() {
echo "This is the construct magic method";
}
}
// Creating object of Magic method class
$obj = new MagicMethod();
?>
OutputThis is the construct magic method
__destruct() Method: In the below example, the MagicMethod class has a magic method __destruct() that gets called automatically when the object of MagicMethod destroys.
PHP
<?php
class MagicMethod {
function __destruct() {
echo "This destruct magic method "
+ "gets called when object destroys";
}
}
$obj = new MagicMethod();
?>
Output This destruct magic method gets called
when object destroys
__call($name, $parameters) Method: This method gets called when a method or property is called which has not been defined.
This method takes two parameters:
- $name: This contains the name of the method which was called.
- $parameters: This is an array of parameters that were given to that method.
PHP
<?php
class MagicMethod {
function __call($name , $parameters){
echo "Name of method =>" . $name."\n";
echo "Parameters provided\n";
print_r($parameters);
}
}
// Instantiating MagicMethod
$obj = new MagicMethod();
$obj->hello("Magic" , "Method");
?>
OutputName of method =>hello
Parameters provided
Array
(
[0] => Magic
[1] => Method
)
__toString() Method: This method gets called when an object is treated as a string. This method is also useful to represent an object as a String.
PHP
<?php
class MagicMethod {
function __toString(){
return "You are using MagicMethod object as a String ";
}
}
$obj = new MagicMethod();
echo $obj;
?>
OutputYou are using MagicMethod object as a String
__get($name) Method: This method gets called when an inaccessible (private or protected ) variable or non-existing variables are used.
PHP
<?php
class MagicMethod {
function __get($name){
echo "You are trying to get '" . $name .
"' which is either inaccessible
or non existing member";
}
}
$obj = new MagicMethod();
$obj->value;
?>
Output You are trying to get 'value' which is either
inaccessible or non existing member
__set($name, $value) Method: This method is called when an inaccessible variable or non-existing variable is tried to modify or alter.
PHP
<?php
class MagicMethod {
function __set($name , $value) {
echo "You are trying to modify '"
. $name . "' with '" . $value .
"' which is either inaccessible
or non-existing member";
}
}
$obj = new MagicMethod();
$obj->value = "Hello";
?>
OutputYou are trying to modify 'value' with 'Hello' which is either inaccessible
or non-existing member
__debugInfo() Method: This method is used when the var_dump() function is called with object as a parameter. This method should return an array containing all the variables which may be useful in debugging.
PHP
<?php
class MagicMethod {
function __debugInfo(){
return array("variable"=> "value");
}
}
$obj = new MagicMethod();
var_dump($obj);
?>
Outputobject(MagicMethod)#1 (1) {
["variable"]=>
string(5) "value"
}
Similar Reads
What are the __construct() and __destruct() methods in a PHP ? The constructor is the OOPs concept in PHP. It is a method that has the same name as the class name. It is defined inside the class and is used to automatically call when the object is created.PHP4 provides the constructor method whereas PHP5 provides the magic method __construct and __destruct. Thi
5 min read
HTTP GET and POST Methods in PHP In this article, we will know what HTTP GET and POST methods are in PHP, how to implement these HTTP methods & their usage, by understanding them through the examples. HTTP: The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a r
4 min read
What is the most used method for hashing passwords in PHP ? Hashing password is a technique of converting a single password into another string called hashed password. The hashed password is generally one-way, i.e. we can't go to the original password from the hashed password. So the thing is why we needed to use hashing to do all this stuff, why going one m
3 min read
What is the use of $GLOBALS in PHP ? In this article, we will discuss $GLOBALS in PHP. $GLOBALS is a superglobal variable used to access global variables from anywhere in the PHP program. PHP stores all global variables in an array called $GLOBALS[index]. Syntax: $GLOBALS['index']=value;value is the input value.The index is the unique
1 min read
How to Create an Object Without Class in PHP ? In PHP, creating an object without a class refers to creating an instance of the stdClass, a built-in PHP class for creating generic objects. It allows developers to instantiate objects without explicitly defining a custom class, often used for dynamic data storage.In this article, we will create an
3 min read
What is the use of array_count_values() function in PHP ? In this article, we will discuss array_count_values() function & its usage in PHP, along with understanding its basic implementation through the illustrations. The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values()
2 min read
What is PHP and Why we use it ? What is PHP? PHP(short for Hypertext PreProcessor) is the most widely used open source and general purpose server side scripting language used mainly in web development to create dynamic websites and applications. It was developed in 1994 by Rasmus Lerdorf. A survey by W3Tech shows that almost 79% o
2 min read
What is the difference between self and $this ? The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class. PHP self operator: The self operator represents the current class and thus is used to access cl
2 min read
What is the use of the $_REQUEST variable in PHP ? Uses of PHP $_REQUEST: The PHP $_REQUEST is a PHP superglobal variable that is used to collect the data after submitting the HTML forms as the $_REQUEST variable is useful to read the data from the submitted HTML open forms.$_REQUEST is an associative array that by default contains contents of an $_
2 min read