Home > OS >  Exception class not found
Exception class not found

Time:12-15

I am trying to define a simple exception hierarchy:

Exception -> ServiceDenied -> IpBlocked

ServiceDenied.php:

<?php
namespace Morpher\Ws3Client;


class ServiceDenied extends \Exception
{
    function __construct(string $message, int $code)
    {
        parent::__construct($message, $code);
    }
}

IpBlocked.php:

<?php
namespace Morpher\Ws3Client;

use Morpher\Ws3Client\ServiceDenied; // this line is greyed out by the IDE

class IpBlocked extends ServiceDenied // this line has the error
{
    function __construct(string $message, int $code)
    {
        parent::__construct($message, $code);
    }
}

Both files are in the same folder.

Now when I run unit tests, I get the following error:

Error : Class 'Morpher\Ws3Client\ServiceDenied' not found
 C:\Code\morpher-ws3-php-client\src\exceptions\IpBlocked.php:6
 C:\Code\morpher-ws3-php-client\vendor\composer\ClassLoader.php:571
 C:\Code\morpher-ws3-php-client\vendor\composer\ClassLoader.php:428

Why am I getting this error and how do I fix it?

Removing the greyed out line does not have any effect. It still says "Class 'Morpher\Ws3Client\ServiceDenied' not found".

Sorry if it's something obvious. I'm new to PHP.

CodePudding user response:

Check how your program is autoloading classes.
You can test if this is the issue if you add require() functions in your classes
e.g. require('ServiceDenied.php'); in IpBlocked.php and then in the file where you test things require('IpBlocked.php');

or just check the autoloader logic...

CodePudding user response:

Being new to PHP, I just blindly did:

composer dump-autoload -o  

as instructed by the person who wrote this code.

@Yavor's answer got me reading about autoloaders and Autoloader optimization which is what that command does, it creates a file that maps class names to file names. While this is good for performance, the linked page specifically discourages optimization in dev environments: adding a new class renders the mapping file obsolete and incorrect, hence the errors.

After I removed the vendor/composer folder as per this answer, things started working again.

  • Related