How to get the path of a derived class from an inherited method?

前端 未结 6 1818
轮回少年
轮回少年 2021-01-30 13:11

How to get the path of the current class, from an inherited method?

I have the following:



        
相关标签:
6条回答
  • 2021-01-30 13:28

    Yes. Building on Palantir's answer:

       class Parent  {
          protected function getDir() {
             $rc = new ReflectionClass(get_class($this));
             return dirname($rc->getFileName());
          }
       }
    
    0 讨论(0)
  • 2021-01-30 13:28

    If you are using Composer for autoloading you can retrieve the directory without reflection.

    $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 讨论(0)
  • 2021-01-30 13:32
    <?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'
    ?>
    

    Please not that if you need to get the dir, directly use __DIR__.

    0 讨论(0)
  • 2021-01-30 13:38

    Using ReflectionClass::getFileName with this will get you the dirname the class Child is defined on.

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

    You can get the class name of an object with get_class() :)

    0 讨论(0)
  • 2021-01-30 13:40

    You can also pass the directory as constructor arg. Not super elegant, but at least you don't have to work with reflection or composer.

    Parent:

    <?php // file: /parentDir/class.php
       class Parent  {
          private $directory;
    
          public function __construct($directory) {
              $this->directory = $directory;
          }
    
          protected function getDir() {
             return $this->directory;
          }
       }
    ?>
    

    Child:

    <?php // file: /childDir/class.php
       class Child extends Parent {
          public function __construct() {
            parent::__construct(realpath(__DIR__));
            echo $this->getDir(); 
          }
       }
    ?>
    
    0 讨论(0)
  • 2021-01-30 13:45

    Don't forget, since 5.5 you can use class keyword for the class name resolution, which would be a lot faster than calling get_class($this). The accepted solution would look like this:

    protected function getDir() {
        return dirname((new ReflectionClass(static::class))->getFileName());
    }
    
    0 讨论(0)
提交回复
热议问题