While developing a WordPress plugin, I stumbled when trying to use PHP's 'DOMDocument' class.
In short, I encountered an error like 'Class 'XXXX\DOMDocument' not found in ...'.
It was just an incorrect class path, but how exactly do you specify class paths in PHP itself?
WHAT TO CHECK WHEN YOU GET A 'CLASS '~' NOT FOUND' ERROR
First, check if you are using 'namespace'.
PHP's built-in classes exist in what is called the 'global namespace'.
// 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' Error
If the error is due to the aforementioned namespace issue, it can be resolved using 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();
}
}You can either explicitly import the class using 'use' or specify the full path when instantiating it with 'new'.
For global functions and classes, you explicitly use a backslash '\' (which is '¥' in Japanese character sets).
ADDITIONAL NOTE: CASES WHERE DOMDOCUMENT ITSELF IS NOT INSTALLED
Reference: Class 'DOMDocument' not found
Depending on your WordPress environment, you might need to install the extension itself, as mentioned in the reference site above.
Recommended PHP Books
There are many PHP books out there, but I'll introduce some that seem relatively easy to read. I believe you'll grasp the concepts if you read any of them thoroughly.
Detailed! PHP 8 + MySQL Introduction Notes: XAMPP + MAMP Compatible
📦