Should I use a backslash before global functions in PHP even if is not needed?

Viewed 484

There is a recommendation on https://phptherightway.com/pages/The-Basics.html using backslash for global functions. Take a look at this code:

<?php

 namespace myspace;
 
 class MyClass
 {
      public $myvar = 'test';
      public function myfunction()
      {
           $withoutBackslash = json_encode($this->myvar);
           $withBackslash    = \json_encode($this->myvar);
          return [$withBackslash, $withoutBackslash];
      }
  }

How is better with or without backslash? I never used them before should I change my code in either direction (removing or adding)?

3 Answers

No, since you do not have global functions, only classes, then there is no point in separate them. They are using \fopen because they have phptherightway\fopen

In that case writing just fopen will refer to phptherightway\fopen instead of global fopen

I think you've missunderstood the idea. Take a look at their example:

<?php
namespace phptherightway;

// Our function name is the same as an internal function.
function fopen()
{
    // Execute the function from the global space by adding '\'
    $file = \fopen();    
}

They've defined an fopen() function that should be called from its namespace: \phptherightway\fopen().

Inside that function, they call the native PHP fopen() function and it needs the backslash to do so (from global namespace) and avoid calling itself.

Imagine that you define the same function name yourself. You will still need to have a way to call the global one. Putting the backslash before the name of the function will forward you to the global namespace, therefore you will call the global one.

There may be tiny performace gain that way, but it's much harder to read. Personally I would not put that backslash unless it is necessarily.

Related