检查该脚本PHP调用的类的位置:s

时间:2010-06-29 15:08:03

标签: php

如果我有一个类(例如数据库),我可以检查试图实例化该类的脚本的位置。

一个例子:

我有一个像这样的示例目录结构:

lib
  Database.class.php
app
  action.class.php

并在action.class.php中:

$db = new Database;

和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
}

我不知道这是否可行

此致 路加

更新:看起来这是可能的,但不是很好的做法(来自下面的答案)谢谢你的时间,我不会因为@Gordons论证而暗示这一点。

3 个答案:

答案 0 :(得分:2)

如果调用实例或它在文件系统中的位置是Database类中的依赖项,则通过构造函数传递它。如果您需要找到文件所在的位置,请使用Reflectionmagic __FILE__ constant,例如

// 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
}

或只是

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

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

您不希望debug_backtrace找出名为Database构造函数的内容。顾名思义,它用于调试目的。根据跟踪堆栈的大小,获取回溯可能会消耗大量时间和资源。传递它更清洁,更快。

此外,如果你的代码的安全性取决于文件所在的位置,那么你会引入对文件系统的依赖,这对我来说是代码味道。

答案 1 :(得分:1)

如果您迫切需要这个,那么debug_backtrace()但是使用

将信息传递给构造函数会更容易
$db = new Database('action.class.php');

但在代码中创建此类依赖项并不是一个好主意。

答案 2 :(得分:-1)

我认为你可以使用$_SERVER['SCRIPT_FILENAME']常量。

如果您需要使用完整堆栈的脚本文件,一些output bufferingdebug_backtrace和努力可以提供。