skip to Main Content

I am trying to define a simple exception hierarchy:

Exception -> ServiceDenied -> IpBlocked

ServiceDenied.php:

<?php
namespace MorpherWs3Client;


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

IpBlocked.php:

<?php
namespace MorpherWs3Client;

use MorpherWs3ClientServiceDenied; // 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 'MorpherWs3ClientServiceDenied' not found
 C:Codemorpher-ws3-php-clientsrcexceptionsIpBlocked.php:6
 C:Codemorpher-ws3-php-clientvendorcomposerClassLoader.php:571
 C:Codemorpher-ws3-php-clientvendorcomposerClassLoader.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 ‘MorpherWs3ClientServiceDenied’ not found".

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

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search