PHP Magic Constants 🎯

beginner
23 min

PHP Magic Constants 🎯

Welcome to our deep dive into PHP Magic Constants! In this lesson, we'll explore a unique aspect of PHP that lets you access predefined values without needing to define them. Let's get started!

What are PHP Magic Constants? πŸ“

In PHP, Magic Constants are automatically defined by the PHP engine and can be used anywhere in your code. They provide various information about the current state of your script, such as file and script details, system information, and more.

File and Script Information πŸ“

Here are some Magic Constants that deal with file and script information:

__FILE__ πŸ“

This constant contains the absolute path of the script currently being executed.

__LINE__ πŸ“

This constant returns the current line number in the script.

__DIR__ πŸ“

This constant contains the directory path of the script currently being executed.

__FUNCTION__ πŸ“

This constant contains the name of the currently active function.

__CLASS__ πŸ“

This constant contains the name of the currently active class.

System Information πŸ“

Here are some Magic Constants that deal with system information:

PHP_VERSION πŸ“

This constant contains the version of PHP currently being used.

PHP_OS πŸ“

This constant contains the name of the operating system the script is running on.

Practical Example 🎯

Let's write a simple PHP script to see these Magic Constants in action:

php
<?php echo "File: " . __FILE__ . "\n"; echo "Line: " . __LINE__ . "\n"; echo "Directory: " . __DIR__ . "\n"; echo "Function: " . __FUNCTION__ . "\n"; echo "Class: " . __CLASS__ . "\n"; echo "PHP Version: " . PHP_VERSION . "\n"; echo "OS: " . PHP_OS . "\n"; ?>

Save this code in a file named magic_constants.php and run it on your server. You'll see the output displaying the values of the Magic Constants.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the `__FILE__` Magic Constant represent?


Stay tuned for our next lesson where we'll delve deeper into PHP Magic Constants and learn how to use them effectively in your projects! 🎯