We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Problem: Loader dir

Hello everyone!

I have a problem with a class load of folders.

I write the code:

<?php
$loader->registerDirs(
    array(
        $config->application->controllersDir,
        $config->application->libraryDir,
        $config->application->modelsDir
    )
)->register();

The problem is that the functions of the folder libraryDir are not initialized.

For example, create a file SizeData.php:

<?php
function SizeData($filesize = 0) {
        $filesize_ed = 'byte';
        if ($filesize >= 1024) {
            $filesize = round($filesize / 1024, 2);
            $filesize_ed = 'kb';
        }
        if ($filesize >= 1024) {
            $filesize = round($filesize / 1024, 2);
            $filesize_ed = 'Mb';
        }

        return $filesize . ' ' . $filesize_ed;
    }

and try to call a function in the controller.

I shows an error: Fatal error: Call to undefined function SizeData() in /var/****



98.9k

Only classes can be autoloaded in PHP, functions cannot be autoloaded, you must move your functions to a class if you want to use autoloaders:

<?php

class MyFunctions
{
    public static function SizeData($filesize = 0) {
        $filesize_ed = 'byte';
        if ($filesize >= 1024) {
            $filesize = round($filesize / 1024, 2);
            $filesize_ed = 'kb';
        }
        if ($filesize >= 1024) {
            $filesize = round($filesize / 1024, 2);
            $filesize_ed = 'Mb';
        }

        return $filesize . ' ' . $filesize_ed;
    }
}

More info: https://stackoverflow.com/questions/4737199/autoloader-for-functions