tags:

views:

133

answers:

3

without telling me to buy a book, would anyone be interested in answering the following question?

if i am in a namespace with a class named foo. and i wanted to build another class called bar. how would i proceed to make foo, aware of bar and vice versa? at what cost? keep in mind that there could potentially be a whole microcosm of useful classes

+4  A: 

No book, but see the namespace documentation

If your classes are in different namespaces:

<?php
namespace MyProject;

class Bar { /* ... */ }

namespace AnotherProject;

class Foo{ /* ... */ 
   function test() {
      $x = new \MyProject\Bar();
   }
}
?>

If the classes are in the same namespace, it's like no namespace at all.

tuergeist
wait... php uses __backslashes__ for namespacing ?? oh my...
Stefano Borini
that is the cruel truth
tuergeist
isn't it ugly??? lol
hab
The cruel and *ugly* truth :/
Justin Johnson
No need to say RTFM.
Filip Ekberg
@Filip: That's the downvote? pffff; nice. The answer the this question was obviously answered by the manual. Ok, 'RTFM' isn't that polite.
tuergeist
Yes, that is the downvote, being mean and using language like that should be punished somehow.
Filip Ekberg
>> If the classes are in the same namespace, it's like no namespace at all.absolutely true. however the down vote comes from the fact that i'm not really interested in the namespace, per se. touchy touchy.
Mike G
@Mike: revisit your question tags! (php, namespaces) and your question did not clarify WHERE your classes were. So I kindly answered the question for all "namespace cases". Very kind of you to to a downvote...
tuergeist
A: 

You can also use other classes from other namespaces with the using statement. The following example implements a couple core class into your namespace:

namspace TEST
{
    using \ArrayObject, \ArrayIterator; // can now use by calling either without the slash
    class Foo
    {
        function __construct( ArrayObject $options ) // notice no slash
        {
            //do stuff
        }
    }
}
Kevin Peno
+2  A: 

About the namespace question, I refer to tuergeist's answer. The OOP aspect, I can only tell that this proposed mutual awareness of Foo and Bar has a slight smell about it. You would rather work with interfaces and let implementation classes have references to the interface. It might be this is called 'dependency inversion'.

interface IFoo {
    function someFooMethod();
}

interface IBar {
    function someBarMethod();
}

class FooImpl1 {
    IBar $myBar;
    function someImpl1SpecificMethod(){
       $this->myBar->someBarMethod();
    }

    function someFooMethod() { // implementation of IFoo interface
       return "foostuff";
    }
}
xtofl