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
How to use the Date and Time in PHP ?
Date and time handling in PHP is crucial for various web applications, ranging from simple date displays to complex calculations involving time zones and intervals. PHP provides a rich set of functions and classes to manage dates and times efficiently. Understanding these functionalities enables dev
2 min read
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
How to get form data using POST method in PHP ?
PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHPâs input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page wh
2 min read
How to get information sent via post method in PHP ?
In this article, we will learn to get information via the post method in PHP. In PHP, we can use the $_POST method as a superglobal variable that is operated to manage form data. After we click on submit button and the page will send the data through the post method. We can use the data after storin
2 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
How to access data sent through URL with GET method in PHP ?
On a website, we often use forms to collect data, login/signup boxes for users, a search box to search through a web page, etc. So input fields are used to make the website interactive and to collect data. But we know that HTML can not store the data in a database so for that we use a backend script
2 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 use array_merge() and array_combine() in PHP ?
In this article, we will discuss about how to use array_merge() and array_combine() functions in PHP. Both functions are array based functions used to combine two or more arrays using PHP. We will see each function with syntax and implementation array_merge() FunctionThis function merges the two or
3 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