2013-02-28 51 views
0

我正在使用抽象Page類在PHP中創建模板系統。我網站上的每個頁面都是它自己的課程,擴展了Page課程。由於不能實例化一個像$page = new Page();這樣的抽象類,我不知道如何在不知道該頁面的類名的情況下實例化擴展頁面的類。在php中使用未知名稱實例化一個類?

如果我在運行時只知道抽象類的名字,是否可以實例化一個擴展抽象類的類?如果是這樣,我該怎麼做呢?


僞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

'get_parent_class' - http://php.net/manual/en/function.get-parent-class.php – 2013-02-28 04:48:29

+0

這就是父母。我知道父類 - 頁 - 但我不知道孩子的類名。 – 2013-02-28 04:50:39

+0

你能提供一些僞代碼嗎?由於某種原因,不完全遵循 – 2013-02-28 04:52:23

回答

1

如果不知道它的名字,就不能實例化一個類。如上所述,您可以使用變量作爲類/函數名稱。你可以擁有所有頁面兒童名單:

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

但話又說回來,如果你不知道這個名字,你不會知道索引要麼。

+0

謝謝!這似乎是完美的工作! – 2013-02-28 05:15:20

1

你c使用函數/類名稱的變量:

class YourExtendedClass { 
    public function example(){ 
     echo 1; 
    } 
} 

$class = 'YourExtendedClass'; 
$t = new $class(); 
$t->example();