What to check when you get a Class ‘~’ not found error[PHP]

While creating a WORDPRESS plug-in, I accidentally stumbled when I tried to use the PHP class “DOMDocument”,
I would like to write an article with a caveat.
It’s a review of what I usually do casually.

In short, I got an error like “Class ‘XXXX\DOMDocument’ not found in …”.
Only the path specification of Class was different, but how was the method of specifying the path of PHP itself?
I will explain that.

What to check when you get a Class ‘~’ not found error

First, make sure you are using a “namespace”.
The class of PHP itself exists in the “global space” in terms of namespace.
The path will change depending on whether you are using a namespace.
example)

// none error
<?php
$dom = new DOMDocument();


// class not found error
<?php

namespace WPplugin;

class testClass{
    public function test()
    {
        $dom = new DOMDocument();
    }
}

If the above error occurs, it will be “class ‘WPplugin\DOMDocument’ not found”.

How to resolve class not found

In the case of the above namespace error, the error can be resolved by the following two methods.

// Import Class using "use"
<?php
namespace WPplugin;

use DOMDocument;

class testClass
{ 
    public function test()
    {
        $dom = new DOMDocument();
    } 
}

// Using Backslash
<?php
namespace WPplugin;

class testClass
{ 
    public function test()
    {
        $dom = new \DOMDocument();
    } 
}

 
Either use “use” to call the Class firmly, or write the path when calling it with new.
For global functions, explicitly write “\” backslash.

Supplement: In some cases, DOMDocument is not installed in the first place

reference:Class ‘DOMDocument’ not found
Depending on the environment where WORDPRESS is installed, there are cases where it is necessary to install the extension itself, as shown in the reference site above.