If I have a class (e.g Database) can I check the location of the script that tried to instantiate this class.
An example:
I have an example dir structure like so:
lib
Database.class.php
app
action.class.php
and in action.class.php:
$db = new Database;
and in Database.class.php
function __construct(){
$name = //some code to find out that app/action.class.php just tried to instantiate me
$name = explode('/',$name);
if($name[0] = 'app') //allow script to use the class
else $this->__destruct; //dont allow other scripts not in app dir for example
}
I dont know if this is possible or not
Regards
Luke
UPDATE: It seems like this is possible but not good practice (from answers below) thank you for your time, I wont be implimenting this mainly due to @Gordons argument.
If the calling instance or it’s location in the filesystem is a dependency in the Database class, then pass it in through the constructor. If you need find out to where the file is located, use Reflection or the magic
__FILE__constant, e.g.or simply
You do not want
debug_backtraceto find out what called the Database constructor. Like the name implies, it is for debugging purposes. Depending on the size of the trace stack, fetching the backtrace can consume a lot of time and resources. Passing it is cleaner and faster.In addition, if you make security of your code depend on where files are located, then you introduce a dependency on the filesystem, which is code smell to me.