22 December 2006
Determining if method is a static class method or dynamic object method
Up until PHP5, there was no way to designate a function as static or instantiated. The difference is small, but important. Object methods can only be called through an instantiated object and have access to a class’s member variables. A static class method does not have access to object data but also needs not be instantiated to a variable.
Often times when coding, I lay all database I/O in a DataAdapter layer. This allows me to code in an ORM style. By virtue of how MySQL handles connections, I just connect to MySQL early in execution and all the class methods just have it available. I can use it like:
foreach (GetPeople() as $personId) {
$person = PersonDataAdapter::getPerson ($personId);
}
This system has worked for me for some time. But today I made a DataAdapter which needed to connect to a Postgres database. This requires I keep track of the connection resources. So this DataAdapter is designed to be instantiated. But since this is unusual for my design of DataAdapters, I decided that any function will default to using the instanicated resource but would connect on its own in case it hadn’t been instantiated.
It’s a pretty easy piece of code:
$parameter = isset ($this)? $this->parameter: CLASSNAME->getParameter();
PHP4 does not have a self keyword so CLASSNAME needs to be manually set.
PHP does try to make your life easier by sometimes setting $this. If a call to a static method in a class occurs from a dynamic method somewhere earlier in execution, $this will be set and refer to that earlier, instantiated class. This too, can be overcome:
$parameter = isset($this) && strtolower (get_class ($this)) == "CLASSNAME"? $this->parameter: CLASSNAME::getParameter();
isset($this) will short circuit if there is no $this anywhere and if there is, it will ensure $this is the same class as the code which is executing.

