How To Use Magic Constants In PHP

How to use magic constants in php

PHP comes built-in with nine pre-defined magic constants for developers to use in their codebase. Their aim is to help developers perform simple tasks without the need to code their own functions. They range in how they are used, but most interestingly unlike normal PHP constants, they are resolved easier at compile time instead of at runtime. Magic constants are what are classed as special constants and are case-insensitive. With that in mind, it is normal (and best) practice to keep them in all uppercase within your codebase. Let's explore the nine different magic constants, and how they work, along with code examples to show you them in action.

What does __LINE__ do, and how does it work?

The most likely simplest magic constant that's available to us is "line". As it might suggest holds the current position (line number) of a given file. This can be useful if you want to debug an application, where a normal stack trace might be overkill. In the example below, when echoing out __LINE__, it outputs "2", as that's the line number it appears on, and again "4", as this is the fourth line in our example PHP code.

<?php
echo __LINE__; # 2
$test = '123';
echo __LINE__; # 4

How does __FILE__ work?

A little more useful in PHP is the "file" magic constant. This will return the given script's full file path with symlinks pre-resolved. Again very useful when debugging, but could also be used when including other files into PHP. If the __FILE__ constant is present in an included file, the returned path will be that of the included. This output depends on where your file lives, but in our example, our file was called "index.php" and with the folder "/var/www/".

# Outputs: /var/www/index.php 
echo __FILE__;

How to use __DIR__ on PHP

The __DIR__ constant in PHP effectively returns the given directory of a file you call it from. It's the same as using the dirname function in PHP coupled with __FILE__. This is arguably the most useful magic constant available and can be used in a number of different scenarios. There will be many times within a given script that you need to from its location, locate something else. Maybe it's removing a file or making a new directory, when using __DIR__ it will help ensure you're in the correct place relative to your script. Similar to __FILE__, if used inside an include, the included file's directory will be returned. It's also good to point out that it does not have a trailing slash on the returned directory name, with the only exception being if it's the root. Using the same example as above, this time we're only getting the directory name which was "/var/www/".

# Outputs: /var/www 
echo __DIR__;

What is __FUNCTION__ in PHP?

The "function" magic constant returns the name of the function currently being run. Coupled with a try/catch statement, can be useful to quickly debug as if the statement was to catch an error, you could log the running function name. For an even better experience use __LINE__ too. If the function is anonymous, it's the "{closure}".

function test() {
 return __FUNCTION__;
}
# Outputs: test
echo test();

How does __CLASS__ work?

Very similar to the other types of constants, the "class" magic constant returns the given class name. The best thing about this constant is it will return the namespaced value of the class and not just the name of the class name. This becomes useful when having classes with similar names, it instantly points you to the right place. If used in a trait method, it returns the name of the class in which the trait was used, not the trait's name. For that, we can use __TRAIT__.

class testClass
{
 public function example() {
 return __CLASS__;
 }
}
$test = new testClass();
# Outputs: testClass
echo $test->example();

How to get the trait name

Traits, a way PHP allows for reusable code, if you require to find out the trait's name, you can use the __TRAIT__ magic constant. Just like __CLASS__, this will return the name of the given trait used, including the namespaced value.

trait TraitExample {
 public function traitName() {
 return __TRAIT__;
 }
}

class testClass {
 use TraitExample;
}

$test = new testClass();
# Outputs: TraitExample
echo $test->traitName();

How to get the name of a method

The easiest way to find the name of a method is by using the __METHOD__ magic constant in PHP. This constant will return the class method name for the given file.

function methodExample()
{
 return __METHOD__;
}
# Outputs: methodExample
echo methodExample();

How to find the current namespace in PHP

Sometimes it can be useful to find the current namespace of a given file in PHP, and for that, you can use the magic constant, __NAMESPACE__. This will return the namespace of the given script it's called from.

namespace Test;

function whatIsMyNamespace()
{
 return __NAMESPACE__;
}
echo whatIsMyNamespace();

What does "::class" do in PHP?

The special magic constant "::class", returns the fully qualified class name when called in PHP. This is extremely useful in keeping your code easier to read when it's required to pass the class name in functions that require it, which is very common in OOP. Instead of passing the full class name every time, instead, you could just use "::class" in the format ClassName::class. Very helpful when used with namespaced classes. One thing to watch out for is that because this is a compile-time constant, it's possible that a class does not exist because autoloading hasn't yet occurred.

class Test
{
 //...
}
echo Test::class;

Conclusion

Getting familiar with and using magic constants in your PHP web applications will help you save time and make your code easier to read. They fulfill common tasks, without the need to have to program something from scratch each time you want to perform one of their tasks. Used in combination with other PHP built-in functions or as part of debugging can make your coding experience a cleaner and better one.

  • The constants are case-insensitive
  • They are resolved at compile time
  • In PHP 8 and above "::class" can be used on objects
  • The magic constants can be used in combination with each other or separately

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all