Dynamically open php file and check if class extends abstract class (for custom module)
<p>I have an admin process that scans some directories and files to see if certain php files extend an abstract class. So I have a directory structure as follows.</p>

<pre><code>/models
/models/Random.php
/models/Payment/Abstract.php
/models/Payment/Cash.php
/models/Payment/Credit.php
/models/Payment/Cheque.php
</code></pre>

<p>cash.php, credit.php and cheque.php extends abstract.php which are named as MyApp_Payment_Cash, MyApp_Payment_Credit, MyApp_Payment_Cheque.php and MyApp_Payment_Abstract.
I need to produce an array that is <code>array('Cash', 'Credit', 'Cheque');</code>. I have code as follows:</p>

<pre><code>$aModules = array();
foreach (new DirectoryIterator(APPLICATION_PATH . '/models/Payment') as $oFile) {
     if (preg_match('/^(.*)\.php$/', $oFile-&gt;getFileName(), $aMatches)) {
          $sName = sprintf('MyApp_Payment_%s', $aMatches[1]);
          if ($sName instanceof MyApp_Payment_Abstract) {
              $aModules[] = $sName;
          }
     }
}
</code></pre>

<p>But that obviously doesn't work (instanceof doesn't work this way on strings). I tried also tried try... catch on <code>new $sName()</code> but PHP threw a fatal when it tried <code>new MyApp_Payment_Abstract</code>.</p>

<p>As you might gather I'm trying to build an extendable payment system that allows new payment methods to be added in the future.</p>

<p>I could change my regex to something like <code>/^(?!Abstract|.*)\.php$/</code> but that seems a rather blunt instrument for a true test.</p>
