我正在使用抽象Page
类在PHP中创建模板系统。我网站上的每个页面都是自己的类,扩展了Page
类。由于无法实例化像$page = new Page();
这样的抽象类,我无法弄清楚如何在不知道页面的类名的情况下实例化扩展页面的类。
如果我在运行时只知道抽象类的名称,是否可以实例化扩展抽象类的类?如果是这样,我将如何做到这一点?
Page类的伪代码:
<?php
abstract class Page{
private $request = null;
private $usr;
function __construct($request){
echo 'in the abstract';
$this->request = $request;
$this->usr = $GLOBALS['USER'];
}
//Return string containing the page's title.
abstract function getTitle();
//Page specific content for the <head> section.
abstract function customHead();
//Return nothing; print out the page.
abstract function getContent();
}?>
加载所有内容的索引页面将包含如下代码:
require_once('awebpage.php');
$page = new Page($request);
/* Call getTitle, customHead, getContent, etc */
各个页面看起来像:
class SomeArbitraryPage extends Page{
function __construct($request){
echo 'in the page';
}
function getTitle(){
echo 'A page title!';
}
function customHead(){
?>
<!-- include styles and scripts -->
<?php
}
function getContent(){
echo '<h1>Hello world!</h1>';
}
}
答案 0 :(得分:1)
您可以为函数/类名使用变量:
class YourExtendedClass {
public function example(){
echo 1;
}
}
$class = 'YourExtendedClass';
$t = new $class();
$t->example();
答案 1 :(得分:1)
如果不知道它的名字,就不能实例化一个类。如上所述,您可以使用变量作为类/函数名称。您可以拥有所有Page子项列表:
abstract class Page {
public static function me()
{
return get_called_class();
}
}
class Anonym extends Page {
}
$classes = get_declared_classes();
$children = array();
$parent = new ReflectionClass('Page');
foreach ($classes AS $class)
{
$current = new ReflectionClass($class);
if ($current->isSubclassOf($parent))
{
$children[] = $current;
}
}
print_r($children);
并获得以下输出
Array ( [0] => ReflectionClass Object ( [name] => Anonym ) )
但话又说回来,如果你不知道名字,你也不会知道索引。