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" ;
}
}
$obj = new MagicMethod();
?>
|
Output
This 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 );
}
}
$obj = new MagicMethod();
$obj ->hello( "Magic" , "Method" );
?>
|
Output
Name 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 ;
?>
|
Output
You 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" ;
?>
|
Output
You 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 );
?>
|
Output
object(MagicMethod)#1 (1) {
["variable"]=>
string(5) "value"
}
Similar Reads
How to use array_pop() and array_push() methods in PHP ?
The array_push() and array_pop() methods in PHP is used to perform insertions as well as deletions from the object. The article below illustrates the usage of these methods: Table of Content Using array_push() MethodUsing array_pop() MethodUsing array_shift()Using array_push() MethodThe array_push()
3 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 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 a
3 min read
What is the difference between Perl and PHP ?
PHP: PHP (Hypertext Pre-processor) is a general-purpose programming language used to designed a website or web applications. It is the server-side scripting language embedded with HTML to develop Static website, Dynamic website or Web applications. It is used to interact with database and display th
2 min read
How to Declare and Initialize 3x3 Matrix in PHP ?
PHP, a widely used scripting language, is primarily known for its web development capabilities. However, it also offers a robust set of features to perform various other programming tasks, including the creation and manipulation of matrices. A matrix is a two-dimensional array consisting of rows and
3 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iteratin
2 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