Php 如何从继承的方法获取派生类的路径?
如何从继承的方法获取当前类的路径? 我有以下资料:Php 如何从继承的方法获取派生类的路径?,php,oop,inheritance,reflection,Php,Oop,Inheritance,Reflection,如何从继承的方法获取当前类的路径? 我有以下资料: <?php // file: /parentDir/class.php class Parent { protected function getDir() { return dirname(__FILE__); } } ?> 与此一起使用将获得定义类子类的目录名 $reflector = new ReflectionClass("Child"); $fn = $reflec
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
return dirname(__FILE__);
}
}
?>
与此一起使用将获得定义类子类的目录名
$reflector = new ReflectionClass("Child");
$fn = $reflector->getFileName();
return dirname($fn);
您可以使用以下命令获取对象的类名:)是。基于帕兰蒂尔的答案:
class Parent {
protected function getDir() {
$rc = new ReflectionClass(get_class($this));
return dirname($rc->getFileName());
}
}
别忘了,因为5.5可以,这比调用get\u class($this)
要快得多。可接受的解决方案如下所示:
protected function getDir() {
return dirname((new ReflectionClass(static::class))->getFileName());
}
如果使用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);
还可以将目录作为构造函数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();
}
}
?>
请不要告诉我,如果你需要目录,直接使用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!!谢谢
<?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();
}
}
?>
<?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'
?>