2012-03-01 62 views
3

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

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

$d = new MongoDate(); 

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

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

有没有解决方法?

+0

阅读[php object inheritance](http://php.net/manual/en/language.oop5.inheritance.php):-) – 2012-03-01 21:20:52

+0

同样在这里,我想从MongoCollection :: find ();'也会受到影响。如果我只是将从find中得到的MongoDate投给我的新类,它是否工作? – 2012-03-01 21:22:48

+1

这里的适配器模式可能更合适。检查出来:http://c2.com/cgi/wiki?AdapterPattern – MitMaro 2012-03-01 21:24:02

回答

5

从它继承!

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 
+0

我想过它,但这不会影响我从'MongoCollection :: find();' – 2012-03-01 21:21:05

+0

你有语法错误。 – 2012-03-01 21:22:07

+0

@PhilippSpieß你应该真的把你的尝试和它是如何出现在你的问题。这样人们就会知道如何更好地帮助你。这是说,请张贴真实的代码,我们会看看它和帮助。 – Iznogood 2012-03-01 21:22:52

2

扩展它。这是一个基本的面向对象原则。

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

这将定义一个新类NewClass将继承老MongoDate类的所有公共和受保护的属性和方法,同时还将有包括newFunction()功能。

0

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