【问题标题】:Basic OO with PHP使用 PHP 的基本 OO
【发布时间】:2009-11-04 08:11:08
【问题描述】:

没有告诉我买书,有人有兴趣回答以下问题吗?

如果我在一个名为 foo 的类的命名空间中。我想建立另一个名为 bar 的类。我将如何继续制作 foo,知道 bar,反之亦然?以什么代价?请记住,可能存在有用类的整个缩影

【问题讨论】:

  • foo 类知道 bar 类还是 foo 实例知道 bar 实例?
  • 这不是关于 PHP 命名空间的问题,而不是关于 OOP 的问题吗?
  • stefano: both =) xtofl: as well

标签: php namespaces


【解决方案1】:

没有书,但是see the namespace documentation

如果您的类位于不同的命名空间中:

<?php
namespace MyProject;

class Bar { /* ... */ }

namespace AnotherProject;

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

如果这些类在同一个命名空间中,那就像根本没有命名空间一样。

【讨论】:

  • 残酷和的真相:/
  • @Filip:这是反对票?噗噗;好的。这个问题的答案显然是由手册回答的。好吧,“RTFM”没那么客气。
  • 是的,那是反对票,卑鄙和使用这样的语言应该受到某种惩罚。
  • >> 如果类在同一个命名空间中,就好像根本没有命名空间。千真万确。然而,否决票来自我对命名空间本身并不真正感兴趣的事实。敏感敏感。
  • @Mike:重新审视你的问题标签! (php, namespaces) 并且您的问题没有说明您的课程在哪里。所以我很乐意回答所有“命名空间案例”的问题。非常感谢您投反对票...
【解决方案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";
    }
}

【讨论】:

    【解决方案3】:

    您还可以通过 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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 2011-03-15
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多