note 101518 deleted from language.constants.predefined by danbrown
| From: | danbrown@php.net | Date: | Wed, 22 Dec 2010 01:23:43 +0000 |
| Subject: | note 101518 deleted from language.constants.predefined by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175128@lists.php.net to get a copy of this message | ||
Note Submitter: mhornes
----
@stefan
You can't replace __DIR__ globally, you have to use dirname( __FILE__ ), it is more easy than
declare a class each php file you use.
For example, I use this option:
Folder tree:
/class/db.php
/class/mysql/mysql.php
/functions/util.php
/index.php
File "/functions/util.php";
<?php
function path() {
if( defined( '__DIR__' ) ) {
return __DIR__ . '/';
}
$d = debug_backtrace();
$dir = dirname( $d[ 0 ][ 'file' ] );
$dir = unixpath( $dir ) . '/';
return str_replace( '//', '/', $dir );
}
function unixpath( $p ) {
return str_replace( '\\', '/', array_pop( explode( ':', $p ) ) );
}
#-------------------------------------------------------------#
File "/index.php"
<?php
require dirname( __FILE__ ) . '/functions/util.php';
require path() . '/class/db.php';
#-------------------------------------------------------------#
File "/class/db.php"
<?php
require path() . 'mysql/mysql.php';
#-------------------------------------------------------------#
File "/class/mysql/mysql.php"
<?php
echo path();
// Output: /home/public_html/class/mysql
You always will need require the principal file using dirname( __FILE__ ), but if you have to
include multiple PHP files in the same file, you ca use the short cut. Of course it isn't the
best way if you can be sure that __DIR__ exists. You either can't define a constant with this,
because if you call that constant from another file, it could have another value that the correct
path.
I hope it helps you and that somebody have another solution!!