Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __DIR__ evaluated runtime (late binding)?

Is it somehow possible to get the location of PHP file, evaluated at runtime? I am seeking something similar to the magic constant __DIR__, but evaluated at runtime, as a late binding. Similar difference with self and static:

__DIR__ ~ self
  ???   ~ static

My goal is defining a method in an abstract class, using __DIR__ which would be evaluated respectively for each heir class. Example:

abstract class Parent {
  protected function getDir() {
    // return __DIR__; // does not work
    return <<I need this>>; // 
  }
}

class Heir extends Parent {
  public function doSomething() {
    $heirDirectory = $this->getDir();
    doStuff($heirDirectory);
  }
}

Obviously, this problem occurs only if Parent and Heir are in different directories. Please, take this into account. Also, defining getDir over and over again in various Heir classes does not seem to be and option, that's why we have inheritance...

like image 347
Pavel S. Avatar asked Aug 07 '13 10:08

Pavel S.


1 Answers

You can add the following code in getDir method of Parent class

$reflector = new ReflectionClass(get_class($this));
$filename = $reflector->getFileName();
return dirname($filename);

Your parent class will look like this

abstract class Parent {
    protected function getDir() {
        $reflector = new ReflectionClass(get_class($this));
        $filename = $reflector->getFileName();
        return dirname($filename);
    }
}

Hoping it will help.

like image 92
Abani Meher Avatar answered Nov 09 '22 18:11

Abani Meher