gpt4 book ai didi

php - 包含外部 php 文件

转载 作者:太空狗 更新时间:2023-10-29 13:55:36 26 4
gpt4 key购买 nike

我正在使用一些 php 代码,比如所有页面都通用的数据库连接,所以我创建了一个包含 php 代码的 php 文件,然后我将这个文件包含在我的 HTML 代码中,所以我想知道包含 php 文件的更好方法,包含函数的更好替代方法。我的示例代码在这里

<?php
include "check_timeout.php";
include "connect_to_db.php";
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
mysql_close($con);
?>
</body>
</html>

提前谢谢你。

最佳答案

您有 4 个选项可供选择。

包含'你的文件.php';
include_once '你的文件.php';
要求 'yourfile.php';
require_once 'yourfile.php';

当然你也可以用"代替'。

除了细微差别外,它们都会做同样的事情。

如果 yourfile.php 不存在,包含文件将忽略该事实,您的 php 页面将继续前进——没有任何 fatal error 。

另一方面,require 会产生 fatal error 。

如果您知道那个文件在那里,那么您选择哪个文件就没有区别。

至于带有 _once 后缀的选项,嗯,与没有 _once 后缀的选项相比,它们往往更慢。因为当您使用 include_once 或 require_once 时,PHP 将做一些额外的工作以确保这些文件真正包含一次 - 如果您不小心编码并且许多文件使用许多包含并且您可能会遇到可能的双重包含情况,则保护您免受双重包含同一文件被包含两次的情况。好吧,_once 选项将阻止这种情况。而且这种检查会带来一些处理成本。

我还注意到您使用 "而不是 ' 作为文件分隔符。没有理由选择 "而不是 ' 除非您将在文件中引用变量名称,例如

$thefile = '你的文件.php;包括“$thefile”;

那么从这 4 个中选出哪些?这完全取决于,如果您认为确实需要强制执行 _once 问题,那么您可以选择 include_once 或 require_once,如果您认为不需要,那么您可以选择 include 或 require。至于 include vs require,这一切都归结为如果您的文件由于某种原因无法访问,您希望您的 PHP 脚本死掉还是继续运行。

如果您对某些速度测试感到好奇,可以查看此处的链接。 http://php.net/manual/en/function.require-once.php

我也在这个主题上找到了这个。

Understanding the difference between require and include According to the PHP manual, require and include "are identical in every way except how they handle failure." However, further reading of the manual suggests another very subtle difference that impacts performance. When you use the require keyword, the named file is read in, parsed, and compiled when the file using the require keyword is compiled. When a file containing the include keyword is compiled, the named file is not read in, parsed, and compiled initially. Only when that line of code is executed is the file read, parsed and compiled. Only use the require keyword if you know you will always need that named file in the current script. If you might use its functions, use include instead. PHP opens up all files that are required, but only opens included files as needed. Additionally, you should also consider using require_once and include_once in place of require and include respectively. In practice, it is more likely that you actually want the functionality provided by the require_once and include_once functions, even though it is much more common to use the require and include keywords respectively. Refer to the following PHP manual pages for more information: include, include_once

source: http://www.stevengould.org/portfolio/developerWorks/efficientPHP/wa-effphp/wa-effphp-a4.pdf

关于php - 包含外部 php 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14079459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com