問題描述
MySQLi 在沒有命名空間的類內部和類外部都可以正常工作.
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
致命錯誤:未找到類Projectmysqli""
"Fatal error: Class 'Projectmysqli' not found"
如何在使用命名空間的類中使用 mysqli?
How do I use mysqli inside a class which uses namespace?
推薦答案
默認情況下,PHP 將嘗試從您當前的命名空間加載類.引用全局命名空間中的類:
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();
請注意,如果您不使用開頭的反斜杠,PHP 將嘗試加載相對于您當前命名空間的類.以下代碼將在名稱空間 ProjectSomeNamespace
中查找名為 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 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(/* ... */);
}
}
這篇關于如何在命名空間中使用 MySQLi的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!