如何从继承的方法获取派生类的路径?

时间:2010-06-10 12:25:02

标签: php oop inheritance reflection

如何从继承的方法获取当前类的路径?

我有以下内容:

<?php // file: /parentDir/class.php
   class Parent  {
      protected function getDir() {
         return dirname(__FILE__);
      }
   }
?>

<?php // file: /childDir/class.php
   class Child extends Parent {
      public function __construct() {
         echo $this->getDir(); 
      }
   }
   $tmp = new Child(); // output: '/parentDir'
?>

__FILE__常量总是指向它所在文件的源文件,而不管继承。
我想获得派生类的路径名称。

有没有优雅的方法呢?

我可以按照$this->getDir(__FILE__);的方式做点什么,但这意味着我必须经常重复自己。我正在寻找一种方法,如果可能的话,将所有逻辑放在父类中。

更新
接受的解决方案(Palantir):

<?php // file: /parentDir/class.php
   class Parent  {
      protected function getDir() {
         $reflector = new ReflectionClass(get_class($this));
         return dirname($reflector->getFileName());
      }
   }
?>

6 个答案:

答案 0 :(得分:66)

使用ReflectionClass::getFileName可以获得定义类Child的目录号。

$reflector = new ReflectionClass("Child");
$fn = $reflector->getFileName();
return dirname($fn);

您可以使用get_class()获取对象的类名:)

答案 1 :(得分:28)

是。以Palantir的答案为基础:

   class Parent  {
      protected function getDir() {
         $rc = new ReflectionClass(get_class($this));
         return dirname($rc->getFileName());
      }
   }

答案 2 :(得分:11)

不要忘了,因为5.5你可以use class keyword for the class name resolution,这比调用get_class($this)快得多。接受的解决方案如下所示:

protected function getDir() {
    return dirname((new ReflectionClass(static::class))->getFileName());
}

答案 3 :(得分:8)

如果您使用 Composer 进行自动加载,则可以检索没有反射的目录。

$autoloader = require 'project_root/vendor/autoload.php';
// Use get_called_class() for PHP 5.3 and 5.4
$file = $autoloader->findFile(static::class);
$directory = dirname($file);

答案 4 :(得分:0)

您还可以将目录作为构造函数arg传递。不是很优雅,但是至少您不必使用反射或作曲家。

父母:

<?php // file: /parentDir/class.php
   class Parent  {
      private $directory;

      public function __construct($directory) {
          $this->directory = $directory;
      }

      protected function getDir() {
         return $this->directory;
      }
   }
?>

孩子:

<?php // file: /childDir/class.php
   class Child extends Parent {
      public function __construct() {
        parent::__construct(realpath(__DIR__));
        echo $this->getDir(); 
      }
   }
?>

答案 5 :(得分:0)

<?php // file: /parentDir/class.php
   class Parent  {
      const FILE = __FILE__;
      protected function getDir() {
         return dirname($this::FILE);
      }
   }
?>


<?php // file: /childDir/class.php
   class Child extends Parent {
      const FILE = __FILE__;
      public function __construct() {
         echo $this->getDir(); 
      }
   }
   $tmp = new Child(); // output: '/childDir'
?>

请不要在需要获取目录的情况下直接使用__DIR__