2010-10-27 55 views
1

我試圖獲取從超類繼承的PHP類的絕對路徑名。它看起來應該很簡單。我想下面的代碼解釋了它儘量簡潔:在PHP中獲取繼承類的路徑名

// myapp/classes/foo/bar/AbstractFoo.php 
class AbstractFoo { 

    public function getAbsolutePathname() { 
     // this always returns the pathname of AbstractFoo.php 
     return __FILE__; 
    } 

} 


// myapp/classes/Foo.php 
class Foo extends AbstractFoo { 

    public function test() { 
     // this returns the pathname of AbstractFoo.php, when what I 
     // want is the pathname of Foo.php - WITHOUT having to override 
     // getAbsolutePathname() 
     return $this->getAbsolutePathname(); 
    } 

} 

的原因,我不希望覆蓋getAbsolutePathname()是,有將是一個很大的類,在擴展AbstractFoo,在潛在的許多不同的地方文件系統(Foo實際上是一個模塊),它看起來像是違反了DRY。

+0

除了它不工作的原因('__FILE__'是在編譯時確定的),你需要的確切原因是什麼文件名?恕我直言,這是內部人員從來不需要的內容之一,但我可能忽視了合法使用。 – Wrikken 2010-10-27 16:46:03

+0

[查找PHP文件(在運行時)類定義]的可能的重複(http://stackoverflow.com/questions/2420066/finding-the-php-file-at-run-time-where-a -class-was-defined) – Gordon 2010-10-27 18:40:39

回答

5

嗯,你可以使用reflection

public function getAbsolutePathname() { 
    $reflector = new ReflectionObject($this); 
    return $reflector->getFilename(); 
} 

我不知道是否會返回的完整路徑,或者只是文件名,但我沒有看到任何其他相關的方法,所以試試看...

+0

謝謝@Wrikken ...這就是我沒有注意到我正在寫什麼而打字...... – ircmaxell 2010-10-27 16:51:58

+0

它確實返回完整路徑。完善! – alexantd 2010-10-28 15:55:02

0

你可以用debug_backtrace破解一些東西,但是仍然需要你明確地覆蓋每個子類中的父函數。

在每個子類中將函數定義爲return __FILE__;要容易得多。 __FILE__將始終替換爲找到的文件名,否則無法完成此操作。

1

據我所知,這裏沒有乾淨的解決方法。魔術常量__FILE____DIR__在解析過程中被解釋,並且不是動態的。

我傾向於做的是

class AbstractFoo { 

    protected $path = null; 

    public function getAbsolutePathname() { 

     if ($this->path == null) 
       die ("You forgot to define a path in ".get_class($this)); 

     return $this->path; 
    } 

} 


class Foo extends AbstractFoo { 

    protected $path = __DIR__; 

} 
+0

+1取代'function getAbsolutePathname(){return __DIR__; }'帶'私人$路徑= __DIR __;'在每個子類,這是至少更短 – meagar 2010-10-27 16:15:47

+0

不需要'保護'而不是'私人'''保護'? – rojoca 2010-10-27 16:26:33

+0

@rojoca當然,你是對的!修正了,謝謝。 – 2010-10-27 16:28:19