PHP namespace issues

I am trying to use an external library. Since there are some conflicts, I use namespaces (php 5.3)

The goal is not to change the external library altogether (just by adding namespaces at the top)

Problem inside the library there are several situations that do not work

  • is_a($obj,'3thpartyclassname') only works if I add a namespace in front of 3thpartyclassname
  • 3rd party uses own classes, but they do not work, only if I added global space ( new \Exception )

Any way to make this work unchanged?

Update use \ Exception as Exception; bug fix 2

I only have problems with is_a and is_subclass_of. Both of them need a namespace and ignore the current namespace.

+7
source share
2 answers

No, you need to make some changes.

 namespace My\Own\Namespace; // declare your own namespace use My\ThirdParty\Component; // import 3rd party namespace $component = new Component; // create instance of it var_dump(is_a($component, 'Component')); // FALSE var_dump($component instanceof Component); // TRUE 

The is_a and is_subclass_of require the full name of the class (including the namespace) to be specified. As far as I know, this does not happen with PHP 5.3.5. Using instanceof should solve both fundamentals.

Importing your own classes, such as Exception, should also work, for example

 namespace My\Own\Namespace; use \Exception as Exception; throw new Exception('something broke'); 

See the chapter in the namespace in the PHP Manual for more information.

+12
source

I don't think there is a way to make is_a () respect relative namespaces (for example, the current namespace or the namespace imported with the use command). This is because it takes a string argument and executes in a different context. Instead, you need to switch to instanceof syntax. No, I don’t think that this will help you avoid collisions between libraries, which are both written against the global namespace, you still have to look for such instances and directly access them.

0
source

All Articles