2010-06-10 227 views
36

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

我有以下几点:

<?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):

​​

回答

26

获取对象的类名是。建立在Palantir的答案:

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

是的,这是Palantir的答案的逻辑结论。 – Jacco 2010-06-10 13:06:44

10

不要忘了,因为5.5可以,这将是比调用get_class($this)快了很多。接受的解决方案是这样的:

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

如果您正在使用作曲为自动加载,你可以检索目录,而不反射。

$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); 
+0

伴侣,我已经花了大约4小时今天搜索一种方法来做到这一点,而不使用反射!谢谢! – 2016-08-17 19:31:11

+0

sweet geesuz !!! – 2016-09-12 03:31:29