2009-11-04 90 views
0

没有告诉我买书,任何人都会有兴趣回答以下问题吗?基本OO与PHP

如果我在名为foo的类的命名空间。我想建立另一个名为bar的课程。我将如何着手制作foo,意识到酒吧,反之亦然?费用是多少?请记住,有可能是有用的类

+0

Foo类意识到栏类或知道酒吧的一个实例的FOO的实例? – 2009-11-04 08:17:19

+1

这不是关于PHP命名空间的这个问题,而不是关于OOP的问题? – xtofl 2009-11-04 08:19:40

+0

stefano:both =) xtofl:以及 – 2009-11-08 04:28:21

回答

4

没有一本书的整体缩影,但see the namespace documentation

如果你的类在不同的命名空间:

<?php 
namespace MyProject; 

class Bar { /* ... */ } 

namespace AnotherProject; 

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

如果类在同一个命名空间,它就像没有名字空间。

+11

wait ... php使用__backslashes__作为命名空间?哦,我的... – 2009-11-04 08:19:50

+3

那是残酷的真相 – tuergeist 2009-11-04 08:20:38

+1

是不是很丑?大声笑 – akif 2009-11-04 08:23:21

0

您还可以使用其他名称空间中的其他类与using语句。下面的示例实现了几个核心类到您的命名空间:

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

关于命名空间的问题,我指的是tuergeist's answer。在OOP方面,我只能说这个建议的相互认识FooBar有一点点关于它的味道。您宁愿使用接口并让实现类具有对接口的引用。这可能是这个被称为'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"; 
    } 
}