Use php namespace inside function
From Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the
global scope) or inside namespace declarations. This is because the
importing is done at compile time and not runtime, so it cannot be
block scoped
So you should put like this, use should specified at the global level
require('/var/load.php');
use test\Class;
function go(){
$go = 'ok';
return $go;
}
echo go();
Check the example 5 in the below manual
Please refer to its manual at http://php.net/manual/en/language.namespaces.importing.php
Using use within a function?
It's because you cannot declare it from within a function. From PHP: Using Namespaces:
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.
You'll have to move it outside of any function or class.
Using function inside PHP Namespace
With the setup you have here. You would have to execute the following to fire that function.
(new MyFunctions\basic)->say_hello("Bob");
(I dont recommend this method, it creates an object for no reason.)
What I'm assuming you wanted was:
namespace MyFunctions;
function say_hello($a)
{
echo "Hello, $a";
}
at which point you could use
// this gives you 'Hello, Bob'
MyFunctions\say_hello("Bob");
Calling a PHP function defined in another namespace without the prefix
PHP 5.6 will allow to import functions with the use
keyword:
namespace foo\bar {
function baz() {
echo 'foo.bar.baz';
}
}
namespace {
use function foo\bar\baz;
baz();
}
See the RFC for more information: https://wiki.php.net/rfc/use_function
Use function of namespace A in function of namespace B
From the PHP manual:
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.
The following example will show an illegal use of the use keyword:
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish; // <-- this is wrong!!!
// ...
}
?>
This is where use
should be put - in the global space:
<?php
namespace Languages;
use Languages\Danish; // <-- this is correct!
function toGreenlandic()
{
// ...
}
?>
PHP | What does 'use function function_name;' (where function is a PHP built-in function) do?
Ok is actually pretty easy, the main issue was, that I did not read properly the documentation or I just miss the part, is true though that the use
keyword is widely used in PHP, besides with different functionality all together.
Either way, thanks for whom helped me figured out in the comment section[ (@riggsfolly, @peterm, @eis, @david) of the question and after good reading and testing I'd decided to post the answer my self.
Quick Answer
The use function [some_function]
is a namespace
which defines / import that function for a particular place, this place being the namespaced section givin possibility to have same named function from different namespace and even modifying the name with alias, both for functions and namespace all together.
It can be a user defined namespace, or the global namespace
In this case, calling built-in function this way merely for style / clarity but also may PHP Performance Tip: Use fully-qualified function calls when working with namespaces
Detailed Answer
So the use
keyword is scattered with these functionalities:
- Namespace Import / Include: Modules (as packages), Classes, Traits, Interfaces, functions, constants
- Use outer scope of variables in closure functions
- Inject traits in Classes.
So my question refers to the first point Import / Include (Functions).
The namespace are somehow more evident when using Classes, as soon as a namespace is declared on the script, that script becomes relative to that namespace and not the global anymore. Hence, if you then call any classes that aren't defined in the very same script without specify the namespace, will result in error, example:
<?php
namespace A\B\C;
class Exception extends \Exception
{
}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>
But even more clear example is this:
<?php
namespace A\B\C;
$b = new Exception('hi'); // Uncaught Error: Class "A\B\C\Exception"
By removing the namespace, it goes back to the global context
<?php
$b = new Exception('hi'); // no errors..
However, this is not happening with the const
and functions
, that's why is little less obvious and will silently fall back to the outer scope if not found.
For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>
Finally, for some example regarding my question:
File functions.php
<?php
namespace MyApp\Package;
//use function var_dump;
function var_dump($var)
{
echo '[', __NAMESPACE__, '] don\'t wnat to do that...<br/>';
}
function explode($separator, $some_string)
{
echo '[', __NAMESPACE__, '] opps, bomb failed :(...<br/>';
}
File index.php
<?php
namespace MyApp;
require_once 'functions.php';
use MyApp\Package; // Demostrate that we can 'import' the entire package namespace
use function MyApp\Package\var_dump; // Import the function only
class A
{
public static function say() {
$a = "a";
$b = "b";
$data = ['a' => $a, 'b' => $b];
echo var_dump($data); // --> Calling the namespaced function
}
public static function sayReal()
{
$a = "a";
$b = "b";
$data = ['a' => $a, 'b' => $b];
echo \var_dump($data); // -> with \ we make the lookup fully-qualified and falls back to global
}
public static function explodeBadBomb($bomb="something to explode")
{
Package\explode(" ",$bomb); // -> demostrate that we can namespaced in withing blocks and statements
}
public static function explodeGooodBomb($bomb="something to explode")
{
echo print_r(\explode(" ", $bomb)); // again calling the built-in
}
}
A::say(); // [MyApp\Package] don't wnat to do that...
A::sayReal(); // array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }
A::explodeBadBomb(); // MyApp\Package] opps, bomb failed :(...
A::explodeGooodBomb(); // Array ( [0] => something [1] => to [2] => explode )
Documentation
- Using namespaces: fallback to global function/constant
- Namespaces
- FAQ: things you need to know about namespaces
More on performance improvement
- PHP RFC: declare(function_and_const_lookup='global')
- [RFC] "use global functions/consts" statement
Related StackOverflow Questions / Answers
- Should a PHP interface have a namespace?
- How and where should I use the keyword "use" in php
- In PHP, what is a closure and why does it use the "use" identifier?
- Use keyword in functions - PHP
Namespace as a parameter in a function in php
Given this method:
public function check_shipping(Order $order, $option) {}
We see that Order
is the typehint for the $order
parameter. Order
and $order
are not two different parameters. Order
is defining the type of $order
.
Here is the PHP Documentation on defining function argument types. You'll notice that PHP's capabilities varies with the PHP version that you're running. PHP 7 introduced scalar typehints such as string
, int
, etc but you could typehint objects since PHP 5.0 and arrays since 5.1.
$option
doesn't have a typehint but you could add one right after the ,
depending on what its type is and your PHP version.
When defining a typehint, you can reference the full namespace:
public function check_shipping(\Store\Model\Order $order, $option) {}
That way you don't have to import the namespace with a use
declaration. (Not saying that's what you want to do in any particular situation. I'm just saying that you can do it that way)
Using namespace in if / else statements
Please see Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.
All use
does is import a symbol name into the current namespace. I would just omit the import and use the fully qualified class name, eg
switch ($api) {
case 'foo' :
require_once('foo.php');
$someVar = new SomeClass();
break;
case 'bar' :
require_once('bar.php');
$someVar = new \xxxx\TheClass();
break;
default :
throw new UnexpectedValueException($api);
}
You can also simply add the use
statement to the top of your script. Adding it does not commit you to including any files and it does not require the symbol to be known, eg
use xxxx\TheClass;
switch ($api) {
case 'foo' :
require_once('foo.php');
$someVar = new SomeClass();
break;
case 'bar' :
require_once('bar.php');
$someVar = new TheClass(); // imported above
break;
default :
throw new UnexpectedValueException($api);
}
Related Topics
Differencebetween Null and Empty
Message: Trying to Access Array Offset on Value of Type Null
PHP MySQL - Insert New Record into Table with Auto-Increment on Primary Key
What Is 22527 in Error_Reporting 22527 of PHPinfo
Understanding PHP Curl_Multi_Exec
How to Remove Empty Paragraph Tags from String
PHP & MySQL: When Exactly to Use HTMLentities
PHP - How to Implement Password Reset and Token Expiry
Php: Catch Exception and Continue Execution, Is It Possible
PHP Artisan Migrate Throwing [Pdo Exception] Could Not Find Driver - Using Laravel
Symfony2: How to Access Service from Template
PHP Date Time Current Time Add Minutes
Openssl Not Working on Windows, Errors 0X02001003 0X2006D080 0X0E064002
PHP - Time Remaining Until Specific Time from Current Time of Page Load