Getting child class info from extends construction
I'm not quite sure how to formulate my question, so sorry in advance for this uninformative title.
So here is the problem. I have a couple of files in the same directory, each of them is a class holder. When i inherit one of the classes i need to know in which fi开发者_运维百科le (or more like the folder) i do it. I don't really like the solution i came to, but still to demonstrate what exactly i mean.foo.php
class Foo {
}
bar.php
include_once 'bootstrap.php' ;
class Bar extends Foo {
}
$bar = new Bar() ;
bootstrap.php
function __autoload( $class ) {
$trace = debug_backtrace() ;
// Here i've got the directory i need:
$folder = dirname( $trace[ 0 ][ 'file' ] ) ;
}
Is there any other (proper) way to get folder name, cause it debug_backtrace is not actually meant for this kind of operations. And not good from the performance point of view either.
Limitation: should work for php 5.2.12
$folder = dirname(__FILE__)
doesn't do the job?
The magic constant __FILE__
reports the file name (with path) of the file it is called in (see the PHP docs):
__FILE__
: The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2,__FILE__
always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
That means you can create a method that returns the classes file name.
For example, in 'test-folder/Foo.php':
class Foo {
function getFile() {
return __FILE__;
}
}
And in 'Bar.php`:
include 'test-folder/Foo.php';
class Bar extends Foo {
function getParentFile() {
return parent::getFile();
}
}
$bar = new Bar();
echo dirname($bar ->getParentFile());
// result: C:\wamp\www\test-folder
EDIT: Ok, so if you want to find out where the parent class is before creating it, this should work (using Reflection):
$reflectedBar = new ReflectionClass('Bar');
$reflectedBarParent = $reflectedBar->getParentClass();
$filename = $reflectedBarParent->getFileName();
精彩评论