2013-04-07 62 views
0

嗨我想讓自己的簡單模板系統類的東西 ,我只是在學習類,所以我試圖用類和對象來做到這一點。需要具有類的模板文件

它的工作原理,如果我把這個在每個文檔的頂部:

$template = new Includes('name', 'path'); 
$include = new Includes('name', 'path'); 

但感覺像它不應該是必要的,它不是那麼漂亮。

這是我的代碼是如何安排現在

的index.php:

<?php 
require_once 'class_include.php'; 
$template->loadTemplate('body'); 

body.php:

<?php require_once 'class_include.php'; ?> 
    <head> 

    <?php $template->loadTemplate('head'); ?> 

</head> 
<body> 

<?php 
    $template->loadTemplate('sidepanel'); 
    $template->loadTemplate('content'); 
?> 
</body> 

class_include.php :

class Includes { 

public function loadTemplate($name, $path = 'template'){ 
    require_once "$path/$name.php"; 
} 
public function loadInc($name, $path = 'inc'){ 
    require_once '$path/$name' . '.php'; 
} 
} 
$template = new Includes('name', 'path'); 
$include = new Includes('name', 'path'); 

錯誤消息:

(! )致命錯誤:調用一個成員函數loadTemplate(c)中的非對象上:\ WAMP \ WWW \項目\模板\ body.php

()!注意:未定義的變量:模板C:\ wamp \ www \ project \ template \ body.php

感謝您提供任何幫助!

回答

0

認爲在你的代碼中,你應該使用靜態方法而不是對象。
的index.php

<?php 
require_once 'class_include.php'; 
Includes::loadTemplate('body'); 

body.php

<head> 
    <?php Includes::loadTemplate('head'); ?> 
</head> 
<body> 
    <?php 
     Includes::loadTemplate('sidepanel'); 
     Includes::loadTemplate('content'); 
    ?> 
</body> 

class_includes.php

class Includes { 

    public static function loadTemplate($name, $path = 'template'){ 
     require_once "$path/$name.php"; 
    } 

    public static function loadInc($name, $path = 'inc'){ 
     require_once '$path/$name' . '.php'; 
    } 
} 
+0

這工作不錯,但什麼是一個靜態方法,什麼是不同的NCES? – objectnobb 2013-04-07 17:00:55

+0

靜態方法(或屬性)允許您在不創建任何實例的情況下使用某個類。 https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods – Yefb 2013-04-07 17:43:23

+0

爲什麼你會想要使用不靜態? – objectnobb 2013-04-07 17:50:20

相關問題