Name of calling class using static methods in PHP
From my question on PHPBuilder:
I’m trying to find the name of the current class when calling a static method. To illustrate, let me define a few classes:
abstract class AbstractClass { public function foo() { return class_name($this); # class_name(); gives just "AbstractClass" } public static function bar() { return class_name($this); } } class ConcreteClassOne extends AbstractClass { public function test_non_static() { return foo(); # gives "ConcreteClassOne" } public static function test_static() { # doesn't work because there's not an instance of the class, obviously # However, I would like to find a way of getting "ConcreteClassOne" as the return value in this context return bar(); } } class ConcreteClassTwo extends AbstractClass { public function test_non_static() { return foo(); # gives "ConcreteClassTwo" } public static function test_static() { # See above return bar(); } }
Any ideas on how to get the desired behavior? Being able to do this would really “DRY up” my code, but I can’t seem to find a way to do it–nothing that I’ve googled for or tried has yielded any results so far.
The reason for this is that I want to use that name in the function. I’m making an implementation of the Active Record design pattern. The classes specify the table names. So, for a subclass named “Ticket”, the table name is “tickets”. Say I’m implementing a static function called “count”, called like so:
Ticket::count();
It needs to execute a query like this:
select count(id) from tickets;
There are other subclasses of this Active Record class, such as User:
User::count();
select count(id) from users;
So on and so forth.