PHP

How to get the child (or child child) class name inside of a parent

I was looking for a function recently that would allow me to complete the activerecord setup within my mvc. Each of my model classes would represent a table within mongo in every sense (down to the name of the model class). This would mean any developer using my framework would never have to physically touch the db (which is cool). After some searching I came across the last post on this stackoverflow thread. The guy pointed out a very very very interesting point.

Say you have a database class called “mongo_db.php” which is the parent of “model.php” which is the parent of “session.php” what would be an easy way of getting “session” (from class name) in mongo_db?


function getCollectionClass(){
    return get_class($this);
}

That’s how! Just slap that in your parent class and call it when you need it and it will output a string of the session.php class name. That is weird especially when normally get_class will output mongo_db when used in mongo_db, PHP moves in mysterious ways :P.

Note:
Of course the theory behind this is that get_class() means get the instance name of the procedure class whilst get_class($this) means get the instance name of the class in $this context…and since $this is actually session.php class it will return session.

Advertisements

One thought on “How to get the child (or child child) class name inside of a parent

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s