• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Computing / What are PHP Namespaces?

What are PHP Namespaces?

Last updated on January 28, 2023 by Sal Ferrarello

Namespaces are used to avoid collisions with functions (as well as constants and class names) in PHP.

Prefixing Functions (before Namespaces)

Before namespaces (using PHP 5.2 and below), when creating a function called output_form() I ran the chance that someone else had the same function name defined somewhere else. This would result in a fatal error.

Fatal error: Cannot redeclare output_form()

To work around this, I would prefix it with both salcode and my project name (e.g. modify_comment) so instead of output_form(), the function was salcode_modify_comment_output_form().

Namespacing Functions

As of PHP 5.3, we can add a namespace instead of prefixing. Instead of salcode_modify_comment_output_form(), I can write

namespace salcode\ModifyComment;

function output_form() {
  // Code here.
}

output_form();

By adding namespace salcode\ModifyComment; at the top of my file, it is as if I’ve prefixed all of the functions in the file (so I no longer have to worry about collisions).

Files in Other Namespaces

What if I want to use my output_form() function from a file that is NOT in the namespace salcode\ModifyComment?

The easiest way to target a function in another namespace is to use the fully qualified name (i.e. the namespace and function name together). When we do this we start the line with a leading slash (\), this tells PHP this namespace and function are independent of any namespace defined for the current file.

echo \salcode\ModifyComment\output_form();

WordPress Hooks and Filters with Namespaces

There are some nuances to using namespaces with WordPress Hooks and Filters. See my other blog post WordPress Hooks and PHP Namespaces for more details.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Computing, Programming Tagged With: namespace

Reader Interactions

Leave a Reply Cancel reply

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

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in