开发者

Check location of a from a class called by that script PHP :s

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.

// action.class.php 
public function initDb()
{
    $this->db = new Database($this);
}

// Database.php
public function __construct($invoker)
{
    // reflective way to get $invokerLocation
    $reflector = new ReflectionClass($invoker);
    $invokerLocation = $reflector->getFileName();
    // check location
}

or simply

// action.class.php 
public function initDb()
{
    $this->db = new Database(__FILE__);
}

// Database.php
public function __construct($invokerLocation)
{
    // check location
}

You do not want debug_backtrace to 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.


If you desperately need this, then debug_backtrace() but it would be easier to pass the information to the constructor using

$db = new Database('action.class.php');

but it isn't a good idea to create such dependencies in your code.


I think you could use the $_SERVER['SCRIPT_FILENAME'] constant.

If you need to full stack of script files used, some output buffering, debug_backtrace and effort could give it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜