如何在require_once中调用类函数中的代码?

时间:2014-03-14 20:15:41

标签: php

如果我创建一个使用通过require_once包含的另一个php文件中定义的变量的类,我会得到以下结果:

  1. 如果require_once位于该类的php文件的顶部,并且该变量在myclass->someFunction()中使用,则会抛出错误:Undefined variable

  2. 如果require_once位于myclass->someFunction()内,则一次,然后抛出错误:Undefined variable

  3. 我该如何妥善处理?

    显示问题的示例:

    test.php的

    <?php
        require_once( "holds_var.php" );
    
        class T
        {
            function __construct()
            {
                $this->useVariable();
            }
    
            function useVariable()
            {
                echo $something;
            }
        }
    
        $t = new T();
    ?>
    

    holds_var.php

    <?php $something = "I am something"; ?>
    

    示例2(使用相同的&#34; holds_var.php&#34;):

    test.php的

    <?php   
        class T
        {
            function __construct()
            {
                //This is ok
                $this->useVariable();
    
                //This throws an error
                $this->useVariable();
            }
    
            function useVariable()
            {
                require_once( "holds_var.php" );
                echo $something;
            }
        }
    
        $t = new T();
    ?>
    

2 个答案:

答案 0 :(得分:2)

使用global关键字:

function useVariable()
    {
        global $something;
        require_once( "holds_var.php" );
        echo $something;
    }

答案 1 :(得分:1)

听起来像global可以帮到你的案子。 http://us3.php.net/manual/en/language.variables.scope.php

holds_var.php

<?php
    $something = "I am something";
    global $something;
?>

test.php的

<?php   
    require_once( "holds_var.php" );
    class T
    {
        function __construct()
        {
            //This is ok
            $this->useVariable();

            //This throws an error
            $this->useVariable();
        }

        function useVariable()
        {
            global $something;
            echo $something;
        }
    }

    $t = new T();
?>

以上代码如何为您服务?