Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

php - How to use MySQLi inside a namespace

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 'Projectmysqli' not found"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 SomeNamespaceFoo();

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 ProjectSomeNamespace for a class named Foo:

namespace Project;
$foo = new SomeNamespaceFoo();

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

namespace Project;

use Mysqli;

class ProjectClass
{
    public static function ProjectClassFunction()
    {
        $db = new Mysqli(/* ... */);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...