An issue about 'require_once' chain

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kgo_yoi
Forum Newbie
Posts: 1
Joined: Sun Apr 27, 2008 7:02 am

An issue about 'require_once' chain

Post by kgo_yoi »

When A.php includes B.php and B.php includes C.php, it make me confusing. :crazy: Mainly, the value of "current work directory" expressed by "./" depends on Where I access the php files. For example,

The directory F:\PHP is used to store php file in my computer, I make a new directory named 'lib' in it to store some applications.

Code: Select all

F:\PHP
    |--lib
         |-- A.php
         |-- Facade.php
    |--Client.php
Code in A.php

Code: Select all

<?php
    class A {
        public function methodA() {
            echo "A::methodA()" . "\n";
        }
    }
?>
Code in Facade.php

Code: Select all

<?php
echo "Current Work Directory is: " . getCWD() . "\n";
 
require_once('./lib/A.php');
class Facade {
    private $a;
    public function Facade() {
        $this->a = new A();
    }
    public function show() {
        $this->a->methodA();
    }
}
?>
 
In Client.php

Code: Select all

<?php
echo "<h1>Current Work Directory is " . getcwd() . "</h1>\n";
require_once('./lib/Facade.php');
 
$facade = new Facade();
$facade->show();
?>
 
When I run Client.php with

Code: Select all

F:\PHP>php -f client.php
It's OK, but

Code: Select all

F:\>php -f PHP\client.php
NOT, because current work directory does not contain the directory named lib. Analogously, http://domain/client.php is OK, and http://domain/dir/client NOT.

What's more, If somebody copies my application(Facade.php and A.php) to his directory named 'library', he will have to modify the Facade.php (modify require_once). I don't want to my client programmer or myself do that. Once something was copied to 'lib', every client programmer can directly use them without any modification. How can I implement that.

Now, my resolution is to force files' location: .php used to provide algorithm must be in 'lib' directory; .php used to show HTML must be in site's root directory. End users should not access something in 'lib', they access files that is in site's root directory, so the current work directory is always site's root. I don't think that is a good resolution.

In Java, .jar files is very convenient, I don't need to modify any code in it. Does PHP have some technic homogeneously.

Thanks!
Post Reply