Forget about late static binding, I need the last static __FILE__

I'm looking for the equivalent of get_called_class() for __FILE__ ... Maybe something like get_included_file() ?

I have a set of classes that would like to know in which directory they exist. Something like that:

 <?php class A { protected $baseDir; public function __construct() { $this->baseDir = dirname(__FILE__); } public function getBaseDir() { return $this->baseDir; } } ?> 

And in another file, in another folder ...

 <?php class B extends A { // ... } class C extends B { // ... } $a = new A; echo $a->getBaseDir(); $b = new B; echo $b->getBaseDir(); $c = new C; echo $c->getBaseDir(); // Annnd... all three return the same base directory. ?> 

Now I could do something ghetto, for example add $this->baseDir = dirname(__FILE__) to each expanding class, but that seems a bit ... ghetto. In the end, we are talking about PHP 5.3, right? Shouldn't it be the future?

Is there any other way to get the path to the file in which the class is declared?

+4
source share
5 answers

what if you do not use __FILE__ , but a separate variable and set the variable to __FILE__ in each class

 class A { protected static $baseDir; protected $filename = __FILE__; // put this in every file public function __construct() { } public function getBaseDir() { return dirname($this->filename) . '<br>'; // use $filename instead of __FILE__ } } require('bdir/b.php'); require('cdir/c.php'); class B extends A { protected $filename = __FILE__; // put this in every file } $a = new A; echo $a->getBaseDir(); $b = new B; echo $b->getBaseDir(); $c = new C; echo $c->getBaseDir(); 

you still have to override the property in each class, but not the method

+1
source

Have you tried to assign it as a static member of a class?

 <?php class Blah extends A { protected static $filename = __FILE__; } 

(Untested, and statics plus class inheritance becomes very funny ...)

+3
source

You can use debug_backtrace () . You probably don't want, however.

0
source

Tested:

  protected static $filename = __FILE__; static::$filename 

Does not work.

It seems that the constant is registered when loading a class that is not "late".

Not sure if this was possible before, but for me it was better to use reflection:

  $basePath = new \ReflectionObject($this); $dir = dirname($basePath->getFileName()); 
0
source

Source: https://habr.com/ru/post/1308103/


All Articles