What does this PHP code mean?
require dirname(__FILE__).'/yahooPHP/lib/Yahoo.inc';
This line is开发者_如何学Python in one file in one directory and I am having trouble determining how to reference a file in another directory.
What does this expression mean and does it imply references must only be within the same directory?
__FILE__
is a Magic Constant that correspond to the full path to the file into which it is written.
This means that dirname(__FILE__)
points to the directory into which your current file (the one in which this is written) is.
So, dirname(__FILE__).'/yahooPHP/lib/Yahoo.inc'
points to :
- The directory into which this line is written,
- And, then, the
yahooPHP
subdirectory of that directory - and the
lib
subdirectory ofyahooPHP
- and the
Yahoo.inc
file into thatlib
directory.
Basically, you have :
your-file.php
yahooPHP/
lib/
Yahoo.inc
http://php.net/manual/en/function.dirname.php
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.
A solution to that, is to prefix all include paths with:
<?php str_replace('//','/',dirname(FILE)); ?>this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.
thus, to include a file that is 1 in the parent directory:
<?php require_once( str_replace('//','/',dirname(FILE).'/') .'../parent.php'); ?>to include a file that is in the same directory:
<?php require_once( str_replace('//','/',dirname(FILE).'/') .'neighbor.php'); ?>to include a file that is in a subdirectory:
<?php require_once( str_replace('//','/',dirname(FILE).'/') .'folder/sub.php'); ?>Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
After checking out the specification. This is actually an example of including specified resource into your PHP script, along with retrieving parent folder path and string concatenation. This works as follow:
require = add file to your PHP script (similar to `include`)
dirname() = get the parent directory of specified path
__FILE__ = this will be resolved to absolute path of the current file
.'/yahooPHP/lib/Yahoo.inc' = string concatenation, so this part simply adds file's path to the rest of the string
So in the end you end up adding a file pointed by a path to the Yahoo.inc file (which should be found in directory relative to the parent directory).
精彩评论