Does PHP know itself?

I’ve run into a problem with a framework I’ve been contributing to. It has a bunch of objects, which look a lot like rows in database tables. So there are pages and each page object is a row in the “pages” table in the database, with a primary key called “page_id”. There are also sections and each section object is a row in the “sections” table in the database with a primary key called “section_id”... you get the picture.

So there’s a parent class called “Model” which figures out the magic table/primary key names in the constructor and can then do a variety of tricks on the generic data set. The various object types such as page then extend this “model” and use its methods. Which was going quite well until I tried actually calling the methods.

Statically.

Because I figured that even if the code was inherited from somewhere else, PHP would know which class had called it in the first place and so I’d be able to reference “self” and know what was happening. So wrong!!

Its a feature of PHP that in fact the self() object for a method called statically will always reference the place the code is actually executing. So in order for me to statically call a method which is going to return me an array of instantiated objects of whatever type I called the method against (still with me??), I must first instantiate an object of that type and call it in the usual way.

So in case you’re wondering what the variables $pointless_page and $pointless_section are doing at the top of my script then now you know! I love the little quirks that programming languages have …

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.