Vaia Vaia - 1 year ago 109
PHP Question

Dynamic file system class to automatically create an instance of a specific class (in PHP and PhpStorm)

I've created a function that loads a specific class and also should create a new instance of this class:

class File {

public static function load($file, $folder = null, $local = false, $classname = null) {
if ($folder == 'root') {
$dir = '';
} elseif ($folder) {
$dir = $folder . '/';
} else {
$dir = 'classes/';
if ($local) {
$root = ROOT_ABS;
} else {
$root = ROOT_CMS_ABS;
require_once $root . $dir . $file . '.php';
// New Instance
if ($folder == null || $classname) {
if (!$classname) {
return new $file();
} else {
return new $classname();

I've built in some extra parameters to specify if my CMS folder should be accessed (
constants). So the minimum default case to load a file and also create an object is e.g.:

$html = File::load('html');


I'm using PhpStorm and usually I could hold Ctrl + Click to jump to a function of an object.

enter image description here

But now PhpStorm can't recognize which class has been loaded. In my example this is because I assign
to this class instead of writing
$router = new AltoRouter();


1) Is there another way that PhpStorm recognized which class I'm referring to?

2) I'm kinda new to OOP in PHP, could I improve my class somehow?


Otherwise the function works fine. So this is more likely an IDE issue.

Answer Source

You can easily solve it by adding inline PHPDoc comment with type hint before such assignment. For example:

/** @var MyClassName $router */
$router = File::load('AltoRouter', 'route');

Other than that: using $router = new AltoRouter(); is much better -- leave actual class loading for class autoloading mechanism (following PSR-4; be it standard these days Composer .. or your own implementation).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download