Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Add a method to a class

Tags:

php

mongodb

pecl

I'm looking for a way to extend a PHP class to add a custom method. In particular I want to add a date-format method to MongoDate (from the PHP MongoDB driver).

I just thought it would be much cleaner, if the MongoDate object received from a Mongo collectio, provides a method to make it readable, and not having the need to call a function or class to do that.

$d = new MongoDate();

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

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

Is there any solution?

like image 335
Philipp Spiess Avatar asked Mar 08 '26 01:03

Philipp Spiess


1 Answers

Inherit from it!

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

Then just implement it:

$d = new myClass ();

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

$d->format(); // the way it would be cleaner
like image 123
Iznogood Avatar answered Mar 09 '26 15:03

Iznogood