Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use php namespace inside function

I get a parse error when trying to use a name space inside my own function

require('/var/load.php');  function go(){    use test\Class;      $go = 'ok';     return $go; }      echo go(); 
like image 791
westnblue Avatar asked Aug 14 '13 09:08

westnblue


People also ask

What is the use of inside function in PHP?

If you put it inside a class or a function, it would execute when the class or function is invoked.

What is the use of namespace in PHP?

A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.

Can I use two namespace in PHP?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

What is the difference between namespace and use in PHP?

Namespace is to avoid class name collisions, so you can have two same class names under two different namespaces. Use is just like PHP include. Please sign in or create an account to participate in this conversation.


1 Answers

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

like image 110
Nishant Avatar answered Sep 20 '22 23:09

Nishant