V
V
VicTHOR2019-05-16 16:26:25
PHP
VicTHOR, 2019-05-16 16:26:25

Why is the array not filled in the class and how to fill with callback?

[changed] Focus on the single
function . If done as it is now, then the output is: - a bunch of arrays (each value prints a new one) - a bunch of NULLs If done a little higher, inside the if check, after the declaration, then the output is: - no NULLs - a bunch of arrays (each value is a new array ) Only in the second case it is logical that each value prints a new one, but why does this happen if the print is taken out of the scope of the check? And why are there empty values? As if everything happens in iteration.. How to fix it?
print_r($this->paths);
print_r($this->paths);

Class CheckImgPath
{
    public function __construct()
    {
        $this->paths = [];
    }

    private function _checkPath($dir)
    {
        $path = scandir($dir);
        foreach($path as $value)
        {
            if ($value == '.' || $value == '..') continue;
            $check = $dir."/".$value;
            if (is_dir($check)) {
                self::checkImg($check);
            } else {
                $brand = $dir;
            }
        }
        return $brand;
    }

    public static function checkImg($arr) 
    {
        $single = new CheckImgPath;
        $single->single($arr);
    }

    private function single($arr)
    {
        if (self::_checkPath($arr)) {
            $this->paths[] = self::_checkPath($arr);
        }
        print_r($this->paths);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VicTHOR, 2019-05-17
@VicTHOR

Remade:

Class CheckImgPath
{
    private $paths = [];

    private function _checkPath($dir)
    {
        global $paths;
        $path = scandir($dir);
        foreach($path as $value)
        {
            if ($value == '.' || $value == '..') continue;
            $check = $dir."/".$value;
            if (is_dir($check)) {
                self::_checkPath($check);
            } else {
                $paths[] = $dir;
            }
        }
    }

    public static function checkImg($userPath) 
    {
        global $paths;
        $single = new CheckImgPath;
        if (empty($paths)) {
            $single->_checkPath($userPath);
        }
    }
}

K
kifirch, 2019-05-17
@kifirch

It's called recursion
And you wrote the monster self, $this all around (plus calls to non-statics as statics and ahhh horror)
Essentially

Class CheckImgPath {
      public static $paths = [];
      // в конструкторе делать ничего, совсем его убери
     // обращения должны быть self::$paths
    
}

You create a shitty mountain (depending on nesting of directories) of CheckImgPath instances, each time $this->paths = [];
But this is not the only problem with this code.
How to do it better - see examples here https://www.php.net/manual/ru/function.scandir.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question