PHP scandir() don't work when is called from other file

82 views Asked by At

I've issue with scandir(), when I'm trying to call method from class that is using scandir() it doesn't work, witch means it doesn't see any dirs.

here's method from file ./Core.php

class Core
{
    public function availableControllers()
    {   
        
        $dir = scandir(__DIR__);
        $count = count($dir);
        $i = 0;
        $availableControllers = array();
        
        while ($i < $count) {
            if (is_dir($dir[$i]) && $dir[$i] !== ".." && $dir[$i] !== ".") {
                array_push($availableControllers, $dir[$i]);
            }
            $i++;
        }
        
        return $availableControllers;
    }

I'm calling this method in ./Engine/ControllerLoader.php (method controllerValid() use avalibleControllers())

<?php
include  __DIR__ . "/../Core.php";
class ControllerLoader
{
    public function load()
    {
        
        $Core = new Core;
        $URI = ControllerLoader::explodeURI();
        $controller = $Core->controllerValid($URI[0]);
        $object = $Core->objectsValid($controller , $URI[2]);
        
        $controllerFullName = $controller."Controller";
        

        if( ControllerLoader::includeControllerFile() !== false && (isset($URI[1]) && is_int($URI[1])) ) 
        {
           
            ControllerLoader::includeControllerFile();
            call_user_func("$controllerFullName::monitor");            
        }
        elseif( ControllerLoader::includeControllerFile() !== false && $object !== false && (is_int($URI[3]) || !isset($URI[3])) )
        {
            ControllerLoader::includeControllerFile();
            call_user_func("$controller::$object", [$URI[3]]);
        }
        else
        {
            return false;
        }
    }

When I'm running method avilableControllers from Core.php file works fine, but it doesn't work when ControllerLoader->load() using it(it returns empty array()). Any idea?

1

There are 1 answers

3
ikyuchukov On

As per PHP's manual:

__DIR__ Is the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.

https://www.php.net/manual/en/language.constants.magic.php

The scandir() will be the directory of your Core.php file if availableControllers() is called.

You can also just check if you are in the right folder when you are using this by doing var_dump(__DIR__) in the method you want to use.