开发者

How do I determine the server path of a file of a class file, from that class's parent class in PHP

I'm trying to find a way to determine the server location of a class from within the class' parent, without hardcoding any values. In other words there is a class called Child.php inside /root/classes/Child/Child.php and it extends Parent.php which is in /root/classes/Parent/Parent.php.

I need a way to have a method inside Parent.php return the path to Child.php

class Parent
{
    // Normal constructor stuff

    public function pathToCl开发者_JAVA百科assFile()
    {
        // return path to class file
    }
}

class Child extends Parent
{
    // Normal constructor stuff
}

I then call

$dude = new Child();
print $dude->pathToClassFile();

Returns

/root/classes/Child/Child.php


You'd have to use Reflection (or at least, the last time I did this). Here's approximately how it works:

parent.php

<?php
class ParentClass {
    protected $reflection;
    function filename( ) {
            return $this->reflect( $this )->getFilename( );
    }

    function reflect( $object ) {
            if( !isset( $this->reflection ) ) {
                    $this->reflection = new ReflectionClass( $object );
            }
            return $this->reflection;
    }
}

child.php:

<?php
require_once( 'parent.php' );
class ChildClass extends ParentClass {
}

$child = new ChildClass( );
echo $child->filename( ) . "\n";


I think this should do it:

public function pathToClassFile()
{
    return __FILE__;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜