phpwordpresspluginspsr-4

class_existst returns false WP plugin development


I am following a Wordpress plugin development course, I am blocked now because the method class_exsists() of PHP cannot find my class even if everything seems ok, what am I missing?

CODE

defined('ABSPATH') or die('(ಠ_ಠ)┌∩┐ NOPE!');

if (file_exists(__FILE__ . '/vendor/autoload.php')) {
  require_once(dirname(__FILE__) . '/vendor/autoload.php');
}

define('PLUGIN_PATH', plugin_dir_path(__FILE__));

if(class_exists('Inc\\Init')){
  Inc\Init::register_services();
}

FOLDERS STRUCTURE

This is the structure


Solution

  • The problem

    The problem is that your autoload file never gets included.

    This if-statement:

    if (file_exists(__FILE__ . '/vendor/autoload.php')) {
    

    will never evaluate as true since __FILE__ returns a string containing the full path and the file name of the current file. So your check is basically:

    if (file_exists('/path/to/file.php/vendor/autoload.php')) {
    

    which you can see looks wrong (since it has the file.php part as well).

    Solution

    You just want to get the folder name, so lets use __DIR__ instead:

    if (file_exists(__DIR__ . '/vendor/autoload.php')) {
        require_once __DIR__ . '/vendor/autoload.php';
    }
    

    You can read more about PHP's magic constants here