简体   繁体   English

将一个 PHP 文件包含到另一个文件中

[英]Include one PHP file into another

I need to include one PHP file into another.我需要将一个 PHP 文件包含到另一个文件中。 The PHP file that needs to be included sits in a separate directory though.不过,需要包含的 PHP 文件位于单独的目录中。 This is how it is set up:这是它的设置方式:

folder1/global-functions.php
folder1/folder2/functions.php

I need to include the 'global-functions.php' in the 'functions.php'我需要在“functions.php”中包含“global-functions.php”

I tried:我试过了:

<?php include("../global-functions.php"); ?>

But this will not work.但这行不通。 It returns this error message:它返回此错误消息:

Warning: include(../global-functions.php) [function.include]: failed to open stream: No such file or directory in /home/user/public_html/wp-content/themes/folder1/folder2/custom_functions.php on line 2警告:include(../global-functions.php) [function.include]:无法打开 stream:/home/user/public_html/wp-content/themes/folder1/folder2/custom_functions.php 中没有这样的文件或目录在第 2 行

Warning: include() [function.include]: Failed opening '../global-functions.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/user/public_html/wp-content/themes/folder1/folder2/custom_functions.php on line 2警告:include() [function.include]: 未能在 / 中打开 '../global-functions.php' 以包含 (include_path='.:/usr/lib/php:/usr/local/lib/php')第 2 行的 home/user/public_html/wp-content/themes/folder1/folder2/custom_functions.php

Try including the file with an absolute path: something like this:尝试使用绝对路径包含文件:如下所示:

<?php include ($_SERVER['DOCUMENT_ROOT']."/folder1/global-functions.php");?>

You are including functions.php in itself.您本身就包含了functions.php。 Change functions.php to global-functions.php.将 functions.php 更改为 global-functions.php。

And just out of curiosity, why have different files for functions?只是出于好奇,为什么函数有不同的文件? Why not make classes and objects and make your life easier?为什么不制作类和对象,让您的生活更轻松?

Your original include fails because... the relative path in your include is relative to the current directory, which in your case is not "folder1/folder2/".您的原始包含失败,因为...包含中的相对路径是相对于当前目录的,在您的情况下不是“folder1/folder2/”。 The current directory is likely to be the page from which you are serving your content.当前目录可能是您从中提供内容的页面。

You need to either use an absolute path (with the help of $_SERVER['DOCUMENT_ROOT'] as in @Coomie's answer) or change your include_path to include the location of your included files (but then you must not use a relative path, but you wouldn't need to anyway).您需要使用绝对路径(在@Coomie 的回答中借助$_SERVER['DOCUMENT_ROOT']的帮助)或更改您的 include_path 以包含您包含的文件的位置(但是您不能使用相对路径,但是反正你不需要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM