PHP

PHP BOOTCAMP: Magic Constants


There are a lot of methods, classes and constants that PHP offers to developers for use.

We’ll talk about the MAGIC CONSTANTS today.

Note: These constants didn’t just appear in the standard PHP library, they were not dropped from heaven and a PHP developer doubling as a magician also didn’t write them. This was actually intended to be funny, so if you didn’t laugh, I might have to do a tutorial on recognizing humorous materials  :smile:

There are about 8 useful and important MAGIC CONSTANTS you can use in PHP

1. __FILE__ – This returns the name and full path of the current file

2. __DIR__ – This returns the current directory

3. __TRAIT__ – This returns the trait name including the namespace it was defined in.

4. __NAMESPACE__ – This returns the namespace of the current file/script

5. __LINE__ – This returns the line number where this constant was used.

6. __METHOD__ – This returns the class method name

7. __CLASS__ – This returns the current class name

8. __FUNCTION__ – This returns the function name as it was declared where this constant was used.

 

CODE TIME

Create a file named magicConstant.php

magicConstant.php

Run the code and check the output

This is mine

 

Look at the results carefully. One output is missing. Can you guess?

Yes!!!, the output of the getTrait() is empty. We have no trait in this class hence no result for that.

Write a trait and write a function to use the __TRAIT__  magic constant.

Check out the source code here

Please if you have any questions or observations, feel free to drop it in the comments section below.

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.