Is it possible to use namespace without a class?
For example:
namespace Foo;
// rest of the procedural code and functions
Asking because I have notion that namespace are only used where there are classes.
Thanks for your help.
Yes, you can use namespace without a class, like:
//demo.php file
namespace FooDemo;
function first() { return "First"; }
function second() { return "Second"; }
function third() { return "Third"; }
//test.php file
require_once 'demo.php';
foreach (array("first","second","third") as $funcs) {
echo call_user_func('FooDemo\\'.$funcs);
}
Did you mean something like this
Yes, it is. See the documentation
.
Extract:
<?php
namespace Foo\Bar;
include 'file1.php';
const FOO = 2;
function foo() {}
class foo
{
static function staticmethod() {}
}
/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO
/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
// method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>
use function My\Full\functionName; //or
//use function My\Full\functionName as func;
functionName();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.