Question

When I call any function without recursion (class is loaded by SPL) - all fine, but if that function is calling itself (recursion) - nothing works.

If I use function without autoloader - all works great. I think that happens because object of class doesn't exist, like with magic methods: you have to use __callStatic, not a __call with abstract using class, I was trying to make this function static oO but nothing works again.

Any ideas how does it possible to use recursion through autoloader?

For example this function from php.net doesn't work in autoloader mode:

function r_implode($glue, $pieces)
{
    foreach ($pieces as $r_pieces)
    {
        if (is_array( $r_pieces )) 
        {
            $r_pieces = r_implode($glue, $r_pieces); 
        }
        else 
        {
            $retVal[] = $r_pieces; 
        }
    }
    return implode($glue, $retVal);
}

class load
{
    public static function init()
    {
        return spl_autoload_register(array(__CLASS__, "hook"));
    }
    public static function quit()
    {
        return spl_autoload_unregister(array(__CLASS__, "hook"));
    }
    public static function hook($class)
    {
        // echo "CLASS IS:$class<br>";
        $lnk=PATH . str_replace("_", "/", $class) . ".php";
        ob_start();
        require $lnk;
        ob_end_clean();
        return $class;
    }
}

So when I add function into a class tools, and call tools::r_implode($a,$b); function doesn't work, but when I insert this function in the same php and call r_implode($a,$b) works.

Was it helpful?

Solution

From your posted info this is not clear. You didn't describe the actual error. But I surmise your problem is actually this:

class tools {

    function r_implode($glue, $pieces)
    {
        $r_pieces = r_implode($glue, $r_pieces); 
    }
}

You have packed that function into a class, and the autoloader may even find it. But you didn't adapt the recursive call. If you don't use tools::r_implode for the recursion, then PHP won't find that function. Static methods need to be named explicitly (with class:: prefix). Keeping the plain function name there won't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top