views:

89

answers:

2

Hey all,

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

+1  A: 

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?

webdestroya
Great thanks. I think I'll just pass it through. Thanks!
Matt
Yea, this is exactly what I have done with my templates, just have a tpl_display(), tpl_set() functions so that I don't need to include a global each time.
webdestroya
+1  A: 

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.

Alix Axel
Thanks. Yah that's not elegant at all!
Matt