views:

83

answers:

2

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?

+2  A: 

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...)

Charles
+1  A: 

what if you dont 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 redeclare the property in each class, but not the method

Galen
Yeah, I was worried that it would come down to an answer like this. Note that if you can require PHP 5.3, you can store the equivalent of dirname(\_\_FILE\_\_) by declaring this in every extending class: protected $dirName = __DIR__;
bobthecow