【问题标题】:Make object available within php functions without passing them or making them global使对象在 php 函数中可用,而无需传递它们或使它们成为全局对象
【发布时间】:2011-02-09 12:59:52
【问题描述】:

这个要求只是为了开发人员的简单性和美观的代码。我正在构建一个模板系统,我真的希望一个对象变量简单地存在于所有函数中。这是一些代码:

图书馆员.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);

...

幻灯片放映.php:

public static function basic($args) {
    echo $librarian; // "Librarian Object"
}

谢谢! 马特·穆勒

【问题讨论】:

    标签: php variables templating


    【解决方案1】:

    你可以有一个你使用的函数:

    public static function basic($args) {
        echo librarian();
    }
    
    // some other file
    function librarian()
    {
        global $librarian;
        // does some stuff
    }
    

    这样您就不必不断地向每个函数添加全局语句。

    这是你的意思吗?

    【讨论】:

    • 是的,这正是我对模板所做的,只是有一个 tpl_display()、tpl_set() 函数,这样我就不需要每次都包含一个全局。
    【解决方案2】:

    我猜你可以使用单例,但这在某种程度上属于global 类别。

    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
    }
    

    你也可以在类之外拥有单例:

    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
    }
    

    你想要的都是不可能的,至少我没有看到任何简单优雅的方法来做到这一点。

    【讨论】:

    • 谢谢。是的,这根本不优雅!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2011-12-05
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多