Magic methods and constants in php

In the last lesson we discussed the access modifiers (public vs private) and their uses.

Today we will learn about magic methods and constant in php. Why we call them magic method and magic constant and how to identify them.

Since OOPS has several magic methods and magic constants which reduces the programming code. that is why it is referred as magic methods and function.

Those methods and constants which starts with double underscore (__construct(), __LINE__)  are termed as magic methods or magic constants.

Magic Constant always starts and ends with double underscore (__) and between these double underscore the name of the constant is uppercase like : (__ LINE__).

However there are some disputes on using the magic methods and constants, since there is slight reduction in the performance and time. So we will be using some of them which are widely accepted and ignoring others.

Here i am listing some of magic methods and function and their description.

Magic Methods and constants Description
__construct() This method is executed just after creating object. It helps in setting value of properties as soon as we create object.
__LINE__ Returns the current line number
__FILE__ Return full path or the filename
__CLASS__ Returns the current class name
__METHOD__ Return the name of the method in which __METHOD__ constant is used.

 

The __construct() magic method

Lets take and example to demonstrate the use of __construct() magic method.

Output : test value

From the above example now it is now clear that the constructor gets executed as soon as the object is created.

I also discussed that it helps in setting value of properties as soon as we create object below is its example :

Output : updated value

 

Now what will happen if we do not provide any argument to the class ?

Warning: Missing argument 1 for MagicMethod::__construct(),

 

To handle such situation if we forget to pass argument in class name we will use the below technique.

write a constructor method without risking an error ?

 

Let’s take an example of magic constant.

output : 

The value from class name MagicConstant is 5
I am in line no 12
file name is C:\xampp\htdocs\PHP\oops\magic-constant.php
Method name is MagicConstant::getValue

 

This is all about today’s lesson. Let’s take a brief review that what we have learnt in this lesson.

We learnt : What is magic methods and constant, magic methods and constants declaration. magic methods and constant uses, In the next lesson we will learn an interesting and important topic which is Inheritance.

Leave a Reply

Your email address will not be published. Required fields are marked *