Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current working directory of an extended class in PHP

I have an abstract class "Class". The class Subclass extends Class. The Class abstract class has the following call:

is_readable('some_file.ext')

How do I force the children of the abstract class to look for the file in the folder they are in, instead of the folder of the parent abstract class, without overriding the method in the children?

I.e. if abstract is in

classes/abstracts/Class.php

and the child is in

classes/children/Subclass.php,

how do I make Subclass.php look for some_file.ext in classes/children/ instead of classes/abstracts, without explicitly defining it in the Subclass?

like image 503
Swader Avatar asked Jun 20 '12 10:06

Swader


1 Answers

You can use ReflectionClass::getFileName() to retrieve the filenames in which the subclasses were defined.

// In Superclass
public function isReadableFileInClassDir($file='somefile.ext') {
    $reflection = new ReflectionClass($this);
    $directory = dirname($reflection->getFileName()) . PATH_SEPARATOR;

    return is_readable($directory . $filename);
}

This works because $this no matter where it is defined will always refer to the instantiated class (and not it's parent even though the $this is found in the parent).

like image 187
Bailey Parker Avatar answered Nov 10 '22 17:11

Bailey Parker