Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call global functions classes from namespace PHP

Tags:

namespaces

php

Is there any way how to avoid to using so often backslash ?

Now if i'm using namespace and calling something global inside it i have to use backslash:

namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"

in that case code inside namespace become really ugly, is there any way how to avoid that situation ???

The example was taken from that url: http://www.php.net/manual/en/language.namespaces.faq.php

But my problem in that, if I need call some built in class from namespace i have to use backslash in front of the name, can I somehow avoid it ?

like image 594
user1016265 Avatar asked Aug 28 '12 10:08

user1016265


People also ask

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.

What is a global class in PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

How does PHP namespace work?

Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts. It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.

What is fully qualified class name PHP?

Fully qualified name. This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar . The namespace \Foo is also a fully qualified name. Relative name. This is an identifier starting with namespace , such as namespace\Foo\Bar .


1 Answers

constants and functions from the global namespace do not have to be prepended with a backslash. PHP will fallback to the global namespace for those on it's own. There is a whole chapter in the PHP manual explaining this:

  • Using namespaces: fallback to global function/constant

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. […] For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

like image 157
Gordon Avatar answered Oct 26 '22 14:10

Gordon