Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forget late static binding, I need late static __FILE__

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

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

<?php

class A {

    protected $baseDir;

    public function __construct() {
        $this->baseDir = dirname(__FILE__);
    }

    public function getBaseDir() {
        return $this->baseDir;
    }
}

?>

And in some other file, in some other 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, like adding $this->baseDir = dirname(__FILE__) to each and every extending class, but that seems a bit... ghetto. After all, we're talking about PHP 5.3, right? Isn't this supposed to be the future?

Is there another way to get the path to the file where a class was declared?

like image 967
bobthecow Avatar asked Apr 27 '10 04:04

bobthecow


2 Answers

ReflectionClass::getFileName

like image 195
olamedia Avatar answered Oct 31 '22 12:10

olamedia


Have you tried assigning it as a static member of the class?

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

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

like image 23
Charles Avatar answered Oct 31 '22 11:10

Charles