Mike G
Mike G

Reputation: 89

Basic OO with PHP

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

Upvotes: 0

Views: 222

Answers (3)

xtofl
xtofl

Reputation: 41519

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";
    }
}

Upvotes: 2

tuergeist
tuergeist

Reputation: 9401

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.

Upvotes: 4

Kevin Peno
Kevin Peno

Reputation: 9196

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

Upvotes: 0

Related Questions