anon
anon

Reputation:

Using namespaces in non-class files

I am creating a function file in PHP, for this I want to use a namespace.

Does the namespace encompass all of the file or does it only cover certain parts?

An example would be:

namespace Functions;

function foo()
{
    return "foo";
}

function bar()
{
    return "bar";
}

Or would it be:

namespace Functions;

function foo()
{
    return "foo";
}

namespace Functions;

function bar()
{
    return "bar";
}

Shown as one file for both the examples

Upvotes: 2

Views: 846

Answers (1)

online Thomas
online Thomas

Reputation: 9381

You can create static classes for that:

namespace helpers;
class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Without you are not using OOP which namespaces are a part of

Upvotes: 2

Related Questions