Name of calling class using static methods

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
boakes
Forum Newbie
Posts: 1
Joined: Mon Nov 05, 2007 1:52 pm

Name of calling class using static methods

Post by boakes »

I'm trying to find the name of the current class when calling a static method. To illustrate, let me define a few classes:

Code: Select all

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.
Post Reply