Cat
Cat

Reputation: 7302

How to masquerade child classes in parent class with autoloading (php)

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).

Upvotes: 0

Views: 442

Answers (3)

Adam Byrtek
Adam Byrtek

Reputation: 12202

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.

Upvotes: 0

Wrikken
Wrikken

Reputation: 70490

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.

Upvotes: 0

Sam Day
Sam Day

Reputation: 1719

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.

Upvotes: 2

Related Questions