PHP Accessing function in global scope from a class method

classfunctionglobalmethodsphp

I have the following simple code:

$a = 'hello';

function myfunc() {
    echo 'in myfunc';
}

class myclass {
    function __construct() {
        myfunc();
        echo $a;
    }
}

$m1 = new myclass();

The echo $a within the method gives an error as you would expect since $a is in the global scope and cannot be accessed from within the class without first declaring it as global. That is documented in the PHP manual.

The call to myfunc() does work and I don't understand why. It is also declared in the global scope but the method can access it without first declaring it as global. I can't seem to find anything in the PHP manual that explains why this works.

Maybe I've been doing PHP for too long and this is something so simple I've forgotten how it works. Any insight or a link to where in the PHP manual it says you can access a global function from within a class method would be appreciated.

thanks in advance.

Best Solution

Functions aren't scoped (except if you use namespaces). Only methods are in classes and variables everywhere.

It's supposed to work; everything is correct: you can call functions, once defined, from everywhere.