Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MySQLi inside a namespace

Tags:

MySQLi works fine inside a class with no namespace and outside a class.

I recently started using namespace and now I have stumbled on a code much like the following:

 namespace Project;   class ProjectClass{        public static function ProjectClassFunction{           $db = new mysql(data, data, data, data);       }   } 

However, it reports back to me with a message

"Fatal error: Class 'Project\mysqli' not found"

How do I use mysqli inside a class which uses namespace?

like image 261
Asko Nõmm Avatar asked Dec 28 '11 23:12

Asko Nõmm


1 Answers

By default, PHP will try to load classes from your current namespace. Refer to the class in the global namespace:

$db = new \mysqli(/* ... */); 

This is the same thing you'd do when referring to a class in a different namespace:

$foo = new \Some\Namespace\Foo(); 

Note that if you left off the beginning backslash, PHP would try to load the class relative to your current namespace. The following code will look in the namespace Project\Some\Namespace for a class named Foo:

namespace Project; $foo = new Some\Namespace\Foo(); 

Alternatively, you can explicitly import namespaces and save yourself ambiguity:

namespace Project;  use Mysqli;  class ProjectClass {     public static function ProjectClassFunction()     {         $db = new Mysqli(/* ... */);     } } 
like image 77
Derek Stobbe Avatar answered Oct 19 '22 21:10

Derek Stobbe