0

I have several namespaces, which have their own exception handlers. I also have a general script which needs to reference one of exception handlers - the namespace required is held in a global string.

namespace myNamespace1;
class NewException extends \Exception
{
    ....
}
namespace myNamespace2;
class NewException extends \Exception
{
    ....
}

The $ref variable is a string containing myNamespace1 or myNamespace2. I want to alias one of the Exceptions using this global variable

global $ref;
$alias = $ref . "\NewException";
define("ex", $alias);
use ex as EX;

This doesn't give an error until I try to throw an EX. The class can then not be loaded. Is it possible to do this?

StripyTiger
  • 877
  • 1
  • 14
  • 31
  • I would say yes but not recommended check this answer: https://stackoverflow.com/questions/43612215/php-class-extends-a-string-variable/43612644 – Ammar Joma Jan 14 '22 at 21:28

1 Answers1

0

In use ex as EX; ex is treated as class name, you can't use constants or variables in this way. If you want to alias class name, you can use class_alias():

global $ref;
class_alias($ref . '\NewException', 'my\Exception');

// ...

throw new \my\Exception();

Note that you can have only one class_alias() call that defines my\Exception, and this alias will be available in other places of project.

rob006
  • 21,383
  • 5
  • 53
  • 74