我正在制作几个网页,其中使用php中的单个函数很多。我想知道我如何能把这个函数在一个外部文件和使用它(我试过包括,但它似乎不工作的方式),就像把所有的javascript在一个文件,并把它放在头。由于
对于PHP代码:
//include($_SERVER['DOCUMENT_ROOT'] . "/path/to/myfunction.inc.php"); preferably:
require_once($_SERVER['DOCUMENT_ROOT'] . "/path/to/myfunction.inc.php");
JS代码:
<head>
<script src="/path/to/script.js" type="text/javascript"></script>
</head>
如果您正在使用类,这里有一个非常简单的方法来包含这些:
$includePath = dirname(__FILE__);
set_include_path( get_include_path() . ';' . $includePath );
spl_autoload_extensions( '.cls.php' );
spl_autoload_register();
那么,总结一下注释解决:
-
每个 php代码都应该以
<?php
开头,即使包含了这些文件,否则php会认为它是原始内容(也就是说进入HTML模式)。 - 文件名必须以引号字符串的形式给出,而不是代码中的字面形式。