【问题标题】:PHP - Add a method to a classPHP - 向类添加方法
【发布时间】:2012-03-01 21:17:28
【问题描述】:

我正在寻找一种方法来扩展 PHP 类以添加自定义方法。特别是我想向 MongoDate 添加一个日期格式方法(来自 PHP MongoDB 驱动程序)。

我只是认为如果从 Mongo 集合中接收到的 MongoDate 对象提供了一种使其可读的方法,并且不需要调用函数或类来做到这一点,它会更简洁。

$d = new MongoDate();

some_date_format($d); // the way it works now

$d->format(); // the way it would be cleaner

有什么解决办法吗?

【问题讨论】:

  • 继续阅读php object inheritance :-)
  • 同样,我希望从MongoCollection::find(); 收到的对象也受到影响。如果我只是将从 find 收到的 MongoDate 转换为我的新课程,它是否有效?
  • 适配器模式在这里可能更合适。看看:c2.com/cgi/wiki?AdapterPattern
  • 谢谢,这个模式看起来很适合这个目的。但我想,由于 PHP 是如此动态,所以会有一种方法来添加一个新方法(我猜 C++ 可以做到这一点,我不确定了)
  • 我刚刚找到了php.net/manual/en/function.runkit-method-add.php,但我想这是个坏主意,runkit PECL 的最后一个版本是 2006 年。我还是会试一试!

标签: php mongodb pecl


【解决方案1】:

继承它!

class myClass extends MongoDate{
    public function format(){
    }
}

那就直接实现吧:

$d = new myClass ();

some_date_format($d); // the way it works now

$d->format(); // the way it would be cleaner

【讨论】:

  • 我想过,但这不会影响我从MongoCollection::find();收到的对象
  • @PhilippSpieß 你真的应该把你尝试过的东西以及它是如何出现在你的问题中的。这样人们就会知道如何更好地帮助你。话虽如此,请发布真正的代码,我们会看看它并提供帮助。
  • @Truth 确实!解决它!谢谢!
  • @PhilippSpieß:没有创建一个Decorator,这就是它的工作原理......如果只有Mongo 有方法来覆盖像PDOsetAttribute(PDO_STATEMENT_CLASS,'someClassExtendingPDOStatement') 这样的类。 ..但不幸的是它没有。
【解决方案2】:

扩展它。这是基本的 OOP 原则。

class NewClass extends MongoDate {
    public function newFunction(){
        //Stuff here.
    }
}

这将定义一个新类 NewClass,它将继承旧 MongoDate 类的所有公共和受保护属性和方法,并且还将包含 newFunction() 函数。

【讨论】:

    【解决方案3】:

    您无法更改 PHP 驱动程序返回的日期类型,因此 lznogood & Truth 的答案是您能做的最好的。

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 2012-01-22
      • 1970-01-01
      • 2022-11-27
      • 2016-04-08
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多