当前位置: 动力学知识库 > 问答 > 编程问答 >

mongodb - How do I get the variable names in an overloaded object in PHP?

问题描述:

I'm using Overloading with PHP, and what I want to do is;

When I'm calling the object, it would look like this.

$obj->person->name->function();

To do so, I use __get and __call functions. They would look something like this:

function __get($field){

return $this;

}

However, I want to know the variable names of person and name, since that can change

whenever. I tried to do like this:

function __get($field){

$array[] = $field;

return new object($array);

}

They get saved, but as I add another line, it just adds it to the array. It does not

clean up after a function was called. I tried to empty the array at __call, but that

didn't help. I wanted to Google this, but so far.. I'm out of luck.

Is there a native function for this in PHP?

-- TOO MUCH TO READ? STOP HERE, THE REST IS JUST MORE EXPLANATION --

However the __call sends the array and sends you to another class that handles

functions that is real.

The reason:

I have a 5 programmers that are used to the mongoDB-class, and we're changing

a large codebase from MongoDB to another DB. With this fix we would be able to change

the whole codebase's DB at once, without much hassle of building query's instead. We just

do the query's in the functions class. (access when __call is called). However, a typical

line for a DB query looks like this today:

$this->db->accounts->update(<array>);

This line connects to the one database, inside that database it connects to accounts.

However, we have some "special" variables, like $core. It looks like this:

$this->db->core->accounts->update(<array>);

That one does not connect to the same database.

What we need is to be able to build a line of objects inside objects, that is dynamic. It needs to find what the names called are, so we can put these in querys. Only for ONE line, not all of them. Its basicly a document-based infrastructure on a key-based database, with a lot of hacking. :-D

Thanks so much!

网友答案:

You need to return a different object while accessing the property.

class TempObj{
  public $table;

  public $db;

  public function __call($name,$arguments){
    switch($name){
      case "update":
        $this->db->query("UPDATE ......");
      break;
    }
  }
}

In your DB class

public function __get($name){
  $obj = new TempObj;
  $obj->table = $name;
  $obj->db =& $this;
  return $obj;
}

This way when you do $this->db->accounts it will return you the object which can handle the __call method for this overloaded property.

分享给朋友:
您可能感兴趣的文章:
随机阅读: