我目前可以进行以下操作:

class SubClass extends SuperClass {
  function __construct() {
    parent::__construct();
  }
}

class SuperClass {
  function __construct() {
    // this echoes "I'm SubClass and I'm extending SuperClass"
    echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__;
  }
}

我想用文件名( __ FILE __ ,但动态评估)做类似的事情;我想从超类知道子类所在的文件。有可能以任何优雅的方式吗?

我知道你可以用 get_included_files() 做些什么,但是这不是很有效,特别是如果我有很多实例。

有帮助吗?

解决方案

您可以使用反射。

$ref = new ReflectionObject($this);
$ref->getFileName(); // return the file where the object's class was declared

其他提示

呃,不是真的,我能想到的。每个子类都需要有一个显式实现的方法,它返回 __ FILE __ ,这首先完全破坏了继承点。

我也很好奇为什么这样的事情会有用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top