Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespaces problems

Tags:

namespaces

php

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 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.

like image 730
johnlemon Avatar asked Mar 17 '11 10:03

johnlemon


People also ask

What problems has namespace solved in PHP?

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.

Are PHP namespaces case sensitive?

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.

Can I use two namespace in PHP?

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.

How do namespaces work in PHP?

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.


1 Answers

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.

like image 54
Gordon Avatar answered Sep 21 '22 19:09

Gordon