【问题标题】:requiring template files with classes需要带有类的模板文件
【发布时间】:2013-03-29 15:35:18
【问题描述】:

您好,我正在尝试制作我自己的简单模板系统之类的东西 我只是在学习类,所以我试图用类和对象来做。

如果我把它放在每个文档的顶部,它会起作用:

$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');  

错误信息:

( ! ) 致命错误:在 C:\wamp\www\project\template\body.php 中的非对象上调用成员函数 loadTemplate()

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

感谢您提供的任何帮助!

【问题讨论】:

    标签: php class function templates require


    【解决方案1】:

    认为在您的代码中,您应该使用静态方法而不是对象。
    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';
        }
    }
    

    【讨论】:

    • 效果不错,但是什么是静态方法,有什么区别呢?
    • 静态方法(或属性)允许您在不创建任何实例的情况下使用类。 en.wikipedia.org/wiki/…
    • 你为什么要使用非静态的?
    • 有时您需要在课程中使用 $this。静态方法的细节是你不创建类的实例,所以 $this 是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多