PHP namespaces (on PHP 5.4)-ThrowExceptions

Exception or error:

I need your help with namespaces.

I have this structure:

/main
    /app
        /files
              /file.php
   /lib
       /Exceptions
             /MyException.php
  config.php

MyException.php


namespace System;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

/**
 * Define a custom exception class
 */
class MyException extends \Exception{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null,$needLog=false) {
        $message = 'My error: '.$message;
        if($needLog) {
            self::logError($message,$code);
        }
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    static function logError($message,$code) {
        $log  = new Logger('System');
        $log->pushHandler(new StreamHandler('../../log/SystemLog.log',Logger::ERROR));

        $log->error('Cod.'.$code.' - '.$message);
    }

    public static function launch($message, $code = 0, Exception $previous = null,$needLog=false) {
        new MyException($message,$code,$previous,$needLog);
    }
}

index.php

use Exceptions\System;
MyException::launch('Unexpected answer',1,null,true);

config.php

include_once('/lib/Exceptions/MyException.php');

And the error is:

( ! ) Fatal error: Class ‘Exceptions\System\SystemException’ not found
in C:\wamp64\www\myRootFolder\main\app\files\file.php on line 109

Maybe I just misunderstand how namespaces work, but I would really like to learn how things work here so I can improve my skills.

Thank you.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *