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 the 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 3thpartyclassnamenew \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.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
Note: Namespace names are case-insensitive. Note: The Namespace name PHP , and compound names starting with this name (like PHP\Classes ) are reserved for internal language use and should not be used in the userspace code.
Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.
A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With