Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

php - calling include from an included file

So, examining this directory structure

  • /include_one.php
  • /include_two.php
  • /directory/main_file.php

Assume that I am in /directory/main_file.php and I call include('../include_one.php'); inside of include_one.php, to include include_two.php. Do I need to call include('include_two.php); or include('../include_two.php');?

So my question is: When including a file, is the 'relative include path' shifted to the included file, or does it remain at the main including file?

I am aware that the best alternative would be to have a config.php which contains the root_path, however this is not possible at this stage.


update:
So, im not sure who is right, as here is my test

directory structure

/include.php
/start/start.php
/folder1/includeone.php
/folder1/folder2/includetwo.php

and here is the contents of each file

start.php

<?php 
  echo 'including ../include.php<br />';
  include('../include.php');
?>

include.php

<?php 
  echo 'including folder1/includeone.php<br />';
  include('folder1/includeone.php');
?>

includeone.php

<?php 
  echo 'including folder2/includetwo.php<br />';
  include('folder2/includetwo.php');
?>

includetwo.php

<?php 
  echo 'done<br />';
?>

and the output is

including ../include.php
including folder1/includeone.php
including folder2/includetwo.php
done

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The "relative include path" is not shifted to the included file... Which means that using relative paths generally ends badly.

A better solution, that I use almost all the time, is to always work with absolute paths -- and you can mix relatives and absolute paths using __DIR__, to get the directory that contains the file where this is written.


For example, in include_one.php, you'd use :

require_once __DIR__ . '/include_two.php';

To include the include_two.php file that's in the same directory as include_one.php.


And, in main_file.php, you'd use :

require_once __DIR__ . '/../include_one.php';

To include the include_one.php file that's one directory up.


With that, your includes will work, no matter from which file they are called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...