user185800
user185800

Reputation:

PHP includes Statement

I was wondering how include worked. i thought it was making 2 files or more into one big file

for example file 1 includes file 2. file 1 is in the root directory while file 2 is in root/include/file2. so if file 2 needed to include something from the root/include directory then instead of putting include("file3.php"); i would need to put include("root/include/file3.php"); so then all 3 files are considered by the server to be one big file.

am i anywhere close to how it actually is?

Upvotes: 0

Views: 259

Answers (4)

rwilliams
rwilliams

Reputation: 21487

From the PHP manual:

Files are included based on the file path given or, if none is given, the include_path specified. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

If a path is defined (full or relative), the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

So if you dont want to worry about specifying the relative paths set your include path to /root/include. You can then just use

include("filename");

in any file. I'd also suggest looking at the function require() as it throws a fatal error if it cannot open the file.

Upvotes: 2

Lucas Jones
Lucas Jones

Reputation: 20183

What include does is it pastes one file into another.

Say you have a.php:

Hello, 

And b.php:

world!

Then c.php:

<?php include "a.php"; include "b.php"; ?>

Will become:

Hello, world!

When parsed by PHP. PHP does some magic stuff, but this is the basic effect.

If you need to use a file from another directory (like "hello/world.php"), you have to use that full relative path, not just the file name.

Upvotes: 0

drAlberT
drAlberT

Reputation: 23208

include gets the contents of a file and puts it in the place you inserted the include statement.

It is important to note that the included file is previously parsed by the PHP interpreter, so you can do things such as

if ( ! @include() ) { echo 'the user edited file has a syntax error, default restored.') }

Upvotes: 0

jjclarkson
jjclarkson

Reputation: 5954

From the documentation:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.

So the interactions between include files depends entirely on what scope you include them with one another. Paths can be given that are full or relative or can be omitted in deference to the include_path.

Upvotes: 1

Related Questions