2009-11-04 93 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"; 
    } 
}