Reputation: 450
I have the following file structure:
www
|-- MyLibrary
| |-- Example.class.php
| +-- someDirectory
| +-- somefile.php
|-- other_file.php
+-- another_file.php
I want to include a file from a class:
<?php
class Example {
public function test(){
include "someDirectory/somefile.php";
}
}
?>
It will throw an error because it's including from an other file/directory than the class. Since I'm writing a library I don't known the directory where the files will be in and the path from the file creating the instance and 'somefile.php'.
So my question is: Is there a way to include 'somefile.php' from 'Example.class.php'?
Upvotes: 0
Views: 36
Reputation: 1142
You can use the __DIR__
constant in PHP
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(
__FILE__
). This directory name does not have a trailing slash unless it is the root directory.
(https://secure.php.net/manual/en/language.constants.predefined.php)
So that will be:
<?php
class Example {
public function test(){
include __DIR__."/../someDirectory/somefile.php";
}
}
?>
With this you use the relative path to the file.
Upvotes: 1
Reputation: 2839
You can get the current path that the file is in.
In the structure you're working, you can rewrite the Example class to this:
<?php
class Example {
public function test(){
include __DIR__ . DIRECTORY_SEPARATOR . "someDirectory/somefile.php";
}
}
?>
The __DIR__
constant will give you the current folder.
Upvotes: 0