how are functions made global in php across modules?

时间:2015-05-04 19:27:36

标签: php function spl-autoload-register

Iam going through some legacy php codebase. I having difficulty understanding how functions are made global in php. Here is the directory structure of the project. The functions defined in GlobalUtilities.php are available in Profile.php without any include_once(../../../GlobalUtilies.php). How is it so?

PHPProject
     com.example.usermanagment
             includes
                    GlobalUtilities.php
             controller
                    Entrycontroller.php
             model
                 classes
                         com
                             example
                                     user
                                         resources
                                                    Profile.php

But there is this file autoloader.php included in GlobalUtilies.php.

`autoloader.php`

spl_autoload_register(function($class) {
    $classFile = dirname(__DIR__)
        . DIRECTORY_SEPARATOR . 'model'
        . DIRECTORY_SEPARATOR . 'classes'
        . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

    if (file_exists($classFile)) {
        include_once($classFile);
    }
});

I looked at document for spl_autoload_register and my understanding is that it is NOT making functions global here

GlobalUtilies.php

require_once('autoloader.php');
......// rest of functions here

EDIT: I just noticed that the php tag is not closed in GlobalUtilities.php. That is , I see only this <?php and NO ?>. will that make the functions defined in this file available globally.

1 个答案:

答案 0 :(得分:0)

spl_autoload_register() makes function as __autoload(). This means that if you try to use an undefined function it will try to include it from other included namespace you use. So if you just have included 'autoloader.php' in GlobalUtilies.php, and you use a namespace like com\example\user\resources\Profile, it will automatically include Profile.php and all it's functions, like configured in autoload function.

    ...
    include_once($classFile);
    ...