Mikayla Maki
Mikayla Maki

Reputation: 473

How is PHP's Closure scope determined and how does it relate to class declaration?

I'm trying to have private classes in PHP. In order to do so, I wrote the following code:

<?php

$UsesPrivateClass = function () {
    if (!class_exists('PrivateClass', false)) {
        class PrivateClass
        {
            function someUsefulMethod()
            {
                return 1;
            }
        }


        class UsesPrivateClass
        {
            function __construct($needsData)
            {
                $this->privateClass = new PrivateClass();
            }

            function getValue()
            {
                return $this->privateClass->someUsefulMethod() + 1;
            }
        }
    }
    //Return a UsesPrivateClassFactory
    return function ($needsData) {
        return new UsesPrivateClass($needsData);
    };
};
$UsesPrivateClass = $UsesPrivateClass();

//Now you can access the methods and data of the private class, without exposing it to the global object!

$usesPrivateClassInstance = $UsesPrivateClass("data needed");

echo $usesPrivateClassInstance->getValue(); //Prints out 2

$x = new PrivateClass(); //Throws exception

The only problem is that the final line, $x = new PrivateClass(); //Throws exception, doesn't throw an exception. And I can't figure out why. Isn't the class declaration bound to the closure object? Or is this one of the rough edges between functional and Object Oriented programming languages (at least, as implemented in PHP)?

Upvotes: 0

Views: 29

Answers (1)

colburton
colburton

Reputation: 4715

PHP does not care about any closure when you define a class, it is always globally and publicly available.

It does not matter how you enclose the class PrivateClass {}, therefore no exception at the last line after you executed UsesPrivateClass(). However, if you do not execute that function, the class will not be available.

Upvotes: 2

Related Questions