PHP namespaces problems
I'm trying to use an external library. Because there are some conflicts I'm using namespaces ( php 5.3 )
The goal is not to change the external library at all ( just adding the namespaces at t开发者_运维知识库he top)
The problem is inside the library there are several situations that don't work
is_a($obj,'3thpartyclassname')
only works if I add the namespace in front of 3thpartyclassname- the 3th party uses native classes but they don't work only if I apped the global space (
new \Exception
)
Any way to make this work with no modifications ?
Update use \Exception as Exception; fix problem 2
I only have problems with is_a and is_subclass_of. Both of them need the namespace and ignore the current namespace.
No, you have to do some modifications
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
methods require you to put in the fully qualified classname (including the namespace). To my knowledge, there is no way around that as of PHP 5.3.5. Using instanceof
should solve both bases though.
Importing the native classes, like Exception should also work, e.g.
namespace My\Own\Namespace;
use \Exception as Exception;
throw new Exception('something broke');
See the chapter on Namespace in the PHP Manual for further information.
I don't think there's any way to make is_a() respect relative namespaces (such as the current namespace or a namespace imported with a use
command). This is because it takes a string argument and executes in a different context. You'd need to switch to the instanceof
syntax instead. So no, I don't think that this will help you avoid collisions between libraries which both are written against the global namespace, you'll still have to find instances like this and address them directly.
精彩评论