views:

33

answers:

3

I have a base class that is inherited by about ten subclasses. Most of these subclasses have very similar behavior, but I want to define specialized methods only for three of them.

Is it possible to masquerade the existence of these classes, by autoloading the parent class every time an object of the child class is instantiated? This way I would not have to define multiple classes with the same code?

E.g.

class ParentClass {
    public function __construct() {
        switch(get_class($this)) {
            case "ChildClass1" : do_stuff() break;
            case "ChildClass2" : do_other_stuff() break;
            default: break;
        }
    }
}

$c1 = new ChildClass1();
$c2 = new ChildClass2();

...and have only one file ParentClass.php (no separate files ChildClass1.php or ChildClass2.php).

+2  A: 

Why don't you just do this?

class ParentClass {
  public function __construct()
  {
    $this->do_stuff();
  }
}

class SpecializedClass
  extends ParentClass
{
  public function __construct()
  {
    // Optional, do the stuff parent does (do_stuff());
    parent::__construct();
    // ... specialized construction logic here
    $this->do_other_stuff();
  }

  // ... specialized methods here.
}

class NormalClass1
  extends ParentClass
{

}

class SpecialClass1
  extends SpecializedClass
{

}

// ... etc.
Sam Day
How does my environment find those classes though? My current setup automatically loads a class if it's in a separate file, but it can't load a class if it's defined in a different class' file.
Cat
Ah I understand what you're asking here. In my opinion, relying on __autoload functionality is a great way to get a confusing codebase very quickly. You should group your related classes into files and require them where needed manually. Using require_once is great because if you have circular dependancies, or a complex dependancy chain, you're not going to include the same set of classes more than once.
Sam Day
A: 

You'd have to add the logic to the __autoload() function, or an spl_autoload_register(), which by string comparison decides what file to load / if it possibly is one of the children of your parent.

Wrikken
A: 

In my opinion it's beneficial to maintain the convention of one class per file. It keeps the autoloader straightforward, facilitates reuse of individual classes and, most importantly, makes the source code easier to navigate and reason about. If you have many classes with common parent, consider moving them to a separate subdirectory and add this directory to autoloader.

This is not necessarily true for languages other than PHP that have better import semantics.

Adam Byrtek