문제

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?

도움이 되었습니까?

해결책

what if you don't 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

다른 팁

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

You could use debug_backtrace(). You probably don't want to, though.

Tested:

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

Doesn't work.

It looks like the constant is registered when the class is loaded which is not "late".

Not sure it was possible before, but what was best for me today is using reflection :

    $basePath = new \ReflectionObject($this);
    $dir = dirname($basePath->getFileName());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top