开发者

Make object available within php functions without passing them or making them global

This requirement is just for simplicity for developers and beautiful code. I'm building a template system and I really would just like an object variable to simply be there in all functions. Here's some code:

Librarian.php:

$class = "slideshow";
$function = "basic";
$args = array(...);
$librarian = $this; // I WOULD LIKE THIS TO BE PRESENT IN CALLED FUNCTION

...

return call_user_func($class.'::'.$function, $args);

...

Slideshow.php:

public static function basic($args) {
    echo $librarian; // "Librarian Object"开发者_如何转开发
}

Thanks! Matt Mueller


You could have a function that you use:

public static function basic($args) {
    echo librarian();
}

// some other file
function librarian()
{
    global $librarian;
    // does some stuff
}

That way you won't have to continually add the global statement to each function.

Is that what you meant?


I guess you could use a singleton but that would somewhat fall into the global category.

class Librarian
{
    static $instance = null;

    function __toString()
    {
        return 'Librarian Object';
    }

    function foo()
    {
        return 'bar';
    }

    function singleton()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new Librarian();
        }

        return self::$instance;
    }
}

function basic()
{
    echo Librarian::singleton(); // Librarian Object
    echo Librarian::singleton()->foo(); // bar
}

You can also have the singleton outside the class:

class Librarian
{
    function __toString()
    {
        return 'Librarian Object';
    }

    function foo()
    {
        return 'bar';
    }
}

function singleton()
{
    static $instance = null;

    if (is_null($instance))
    {
        $instance = new Librarian();
    }

    return $instance;
}

function basic()
{
    echo singleton(); // Librarian Object
    echo singleton()->foo(); // bar
}

What you want isn't possible, at least I don't see any simple or elegant way to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜