Skip to main content

Benjamin Oakes

Photo of Ben Oakes

Hi, I'm Ben Oakes and this is my geek blog. Currently, I'm a Ruby/JavaScript Developer at Liaison. Previously, I was a Developer at Continuity and Hedgeye, a Research Assistant in the Early Social Cognition Lab at Yale University and a student at the University of Iowa. I also organize TechCorridor.io, ICRuby, OpenHack Iowa City, and previously organized NewHaven.rb. I have an amazing wife named Danielle Oakes.

Filtering for the PHP category. Clear

PHP: The Right Way

by Ben

An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web

Source: PHP: The Right Way

I rarely write PHP anymore, but this seems like a good resource.

 

 

Name of calling class using static methods in PHP

by Ben

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.