Note that there are some explanatory texts on larger screens.

plurals
  1. POInstantiate a class with an unknown name in php?
    text
    copied!<p>I'm using an abstract <code>Page</code> class to create a template system in PHP. Each page on my website is its own class extending the <code>Page</code> class. Since one cannot instantiate an abstract class like <code>$page = new Page();</code> I can't figure out how to instantiate the extending-page's class without knowing that page's class name. </p> <p>Is it possible to instantiate a class that extends an abstract class if I only know the name of the abstract class at run time? If so, how would I go about doing that? </p> <hr> <p>Pseudocode of the Page class:</p> <pre><code>&lt;?php abstract class Page{ private $request = null; private $usr; function __construct($request){ echo 'in the abstract'; $this-&gt;request = $request; $this-&gt;usr = $GLOBALS['USER']; } //Return string containing the page's title. abstract function getTitle(); //Page specific content for the &lt;head&gt; section. abstract function customHead(); //Return nothing; print out the page. abstract function getContent(); }?&gt; </code></pre> <p>The index page that loads everything would have code like this:</p> <pre><code>require_once('awebpage.php'); $page = new Page($request); /* Call getTitle, customHead, getContent, etc */ </code></pre> <p>The individual pages would look like:</p> <pre><code>class SomeArbitraryPage extends Page{ function __construct($request){ echo 'in the page'; } function getTitle(){ echo 'A page title!'; } function customHead(){ ?&gt; &lt;!-- include styles and scripts --&gt; &lt;?php } function getContent(){ echo '&lt;h1&gt;Hello world!&lt;/h1&gt;'; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload