难以在html页面上从php函数打印文本

时间:2016-06-28 21:49:19

标签: php html

以下是我发生的事情的一个例子:

的common.php

<?php
class Common {
    function test() {
        echo 'asdf;
    }
}?>

webpage.php

<?php 
require_once("common.php");
?>

<html>
<body>
    <?php test(); ?>
</body>
</html>

无论我尝试过什么,我都无法通过功能测试将任何文本打印到页面上。根据我使用的实际网页,以及“&#39;&#39;线路没有加载包含的那部分。我一直在寻找过去一小时来解决这个问题,我做错了什么?

2 个答案:

答案 0 :(得分:3)

你错过了一个'闭包也不需要一个类,你应该只有函数定义

<?php
function test() {
    echo 'asdf';
}
?>

答案 1 :(得分:3)

<?php
class Common {
     function test() {
        echo 'asdf'; // missing a ' closure added
    }
}?>

您可以使用此类的对象

来访问此功能
<?php 
require_once("common.php");

// instantiate the class before you use it.

$common = new Common(); // Common is a object of class Common
?>

<html>
<body>
    <?php echo $common->test(); ?>
</body>
</html>

或者,如果您不想拥有$common变量,可以将该方法设为静态。

<?php
class Common {
    static function test() {
        echo 'asdf';
    }
}?>

然后你要做的就是调用方法:

<html>
<body>
    <?php echo Common::test(); ?>
</body>
</html>