Jac*_*cco 39 php oop reflection inheritance
如何从继承的方法获取当前类的路径?
我有以下内容:
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
return dirname(__FILE__);
}
}
?>
Run Code Online (Sandbox Code Playgroud)
和
<?php // file: /childDir/class.php
class Child extends Parent {
public function __construct() {
echo $this->getDir();
}
}
$tmp = new Child(); // output: '/parentDir'
?>
Run Code Online (Sandbox Code Playgroud)
该__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());
}
}
?>
Run Code Online (Sandbox Code Playgroud)
Pal*_*tir 69
使用ReflectionClass::getFileName它将获得Child定义类的dirname .
$reflector = new ReflectionClass("Child");
$fn = $reflector->getFileName();
return dirname($fn);
Run Code Online (Sandbox Code Playgroud)
您可以使用get_class():) 获取对象的类名
Art*_*cto 30
是.以Palantir的答案为基础:
class Parent {
protected function getDir() {
$rc = new ReflectionClass(get_class($this));
return dirname($rc->getFileName());
}
}
Run Code Online (Sandbox Code Playgroud)
Ian*_*hek 12
不要忘记,从5.5开始,您可以使用class关键字进行类名解析,这比调用快得多get_class($this).接受的解决方案如下所示:
protected function getDir() {
return dirname((new ReflectionClass(static::class))->getFileName());
}
Run Code Online (Sandbox Code Playgroud)
如果您使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32912 次 |
| 最近记录: |