[英]How to include a php file in a file which is already included in many other pages PHP
Can it be possible to include a PHP
file into another file which is already included in many other files on different paths 是否可以将
PHP
文件包含到另一个文件中,而该文件已经包含在其他路径中的许多其他文件中
For example I have the following files and directories: 例如,我有以下文件和目录:
domain/include/header.php
domain/include/body.php
domain/include/user_data.php
header.php
file contains user_data.php
and header.php
file itself contained in many other pages on different location: header.php
文件包含user_data.php
, header.php
文件本身包含在其他页面的不同位置:
domain/index.php
domain/home/index.php
domain/home/user/index.php
I want to access my user_data.php
file within one( ie header.php ) and don't want to include it again and again in each file. 我想访问我的
user_data.php
文件( 即header.php ),并且不想在每个文件中一次又一次地包含它。
How is this possible? 这怎么可能?
参见include_once
和require_once
Yeah why not. 是的,为什么不呢。 You can create master include file and that file includes all other files from the directory.
您可以创建主包含文件,并且该文件包括目录中的所有其他文件。
So your header.php file will look something like this, 因此,您的header.php文件将如下所示:
<?php
include('user_data.php'); // Assuming file is in same location.
Now include only header.php
file where every you want, it will automatically includes user_data.php
along with it. 现在,仅在每个所需的位置包含
header.php
文件,它将自动包含user_data.php
。
Extra: 额外:
This is useful for including database connection files. 这对于包括数据库连接文件很有用。
You can also use this file include root level JS and CSS so you don't have include those assets on every page. 您还可以使用包含根级别JS和CSS的此文件,因此不必在每个页面上都包含这些资产。
Using include_once() is good practice, as if you have included user_data.php
file somewhere in other files and it also gets include from the hedaer.php
file, It won't get included twice. 使用include_once()是一个好习惯,就像您已经将
user_data.php
文件包含在其他文件中的某个位置,并且它也会从hedaer.php
文件中包含include hedaer.php
,不会被包含两次。
As that is all include_once() does, it includes the file content only once per execution. 就像include_once()所做的一样,它每次执行仅包含一次文件内容。
The only difference between include() and include_once() that if the code from a file has already been included, it will not be included again, and include_once returns TRUE .
include()和include_once()之间的唯一区别是,如果已经包含了文件中的代码,则不会再次包含它,并且include_once返回TRUE 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.