Getting current extended class working directory in PHP

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

is_readable('some_file.ext') 

How to force children of an abstract class to search for a file in the folder in which they are located, instead of the folder of the parent abstract class without overriding the method in the children?

those. if the abstraction is in

classes / abstract / Class.php

and the child is in

classes / children / Subclass.php,

how to make Subclass.php look for some_file.ext in classes / children / instead of classes / abstracts, without explicitly defining it in a subclass?

+4
source share
3 answers

You can use ReflectionClass::getFileName() to get the names of files in which 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 regardless of where it is defined, will always refer to the instance class (and not to the parent, even if $this found in the parent).

+10
source

You might be able to use something like the following:

 is_readable(dirname(__FILE__).DIRECTORY_SEPARATOR.'some_file.ext'); 

The dirname method returns the directory of the file that you pass to it.

See Magic Constants for more information on __FILE__

EDIT

In the child class, include the member variable set to __FILE__ and specify that in the abstract class.

Child class

 var $source_location = __FILE__; 

Abstract class

 is_readable($this->source_location.DIRECTORY_SEPARATOR.'some_file.ext'); 
0
source

I believe that you have a good reason for saving classes and subclasses in different folders on your file system, but consider loading classes based on Zend autoload or namespace - this will not work in your case ...

Instead of having this architecture:

 classes | - abstracts | - AbstractClass1.php | - AbstractClass2.php | - children | - ChildClass1.php | - ChildClass2.php 

consider this:

 classes | - AbstractClass1.php | - AbstractClass2.php | - AnotherClass.php | - AbstractClass1 | - ChildClass1.php | - ChildClass12.php | - AbstractClass2 | - ChildClass2.php | - ChildClass22.php | - AnotherClass | - ClassA.php | - ClassB.php | - ClassB | - ClassBA.php 

In this architecture, it is clear that ClassBA , which is in the classes/AnotherClass/ClassB path, extends ClassB , which extends AnotherClass . Now you can use namespaces (when using PHP 5.3 or lt;) or by naming your classes, for example class AnotherClass_ClassB_ClassBA { ... } (Zend class naming convention). You can use the Zend autoloader (e.g..) ...

0
source

All Articles