user2287474 user2287474 - 2 years ago 61
PHP Question

Dynamically generate method that doesn't exist?

I'm trying to write a wrapper for the new MongoDB driver to work with code written for the old driver.

The old way of using Mongo in PHP was like this:

$connection = new Mongo('mongodb://username:password@');
$db = $connection->theDatabaseYouWantToConnectTo;
$collection = $db->aCollectionYouWantToDoStuffWith;
'someColumnName' => 'someDataForTheCell'

My question is, how does these parts work?

$db = $connection->theDatabaseYouWantToConnectTo;
$collection = $db->aCollectionYouWantToDoStuffWith;

are NOT methods, so how would my wrapper class understand what these are?

Here is kind of a skeleton for the wrapper class I'm trying to write.

class Mongo{

var $native_mongo_instance;

function __construct($uri){

$native_mongo_instance = new MongoDB\Driver\Manager($uri);



public function set_native_mongo_instance($native_mongo_instance){

$this->native_mongo_instance = $native_mongo_instance;


public function get_native_mongo_instance(){

return $this->native_mongo_instance;


public function find(){


public function insert(){


public function remove(){


Answer Source

Here you can find a full reference of magic methods in PHP. The one that you're looking for is __get() (here's C code of the legacy driver).

Also to not reinvent the wheel (or for learning purposes), you may take a look at alcaeus/mongo-php-adapter which provides old API atop new driver and library.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download