doudui9516 2016-06-02 05:54
浏览 40
已采纳

包含文件时的Var可见性

How to make variables visible when including some file. For example:

code.php:

<?php
   global $var; $var = "green";
?>

index.php:

<?php

include("code.php");

Function index(){
   echo "The apple is $var";
}

?>

Please note that in code.php there are a lot of global variables (~150 variables) and all variables are used in many different functions inside the index.php.

  • 写回答

2条回答 默认 最新

  • duang5049 2016-06-02 05:58
    关注

    This is an issue to do with variable scope, plus you do not need to be defining $var as a global.

    When you include a file, you can imagine in your head that it is just copy-pasting the contents of the other file into the current file.

    E.g.

    code.php

    $includedName = 'Tom';
    

    index.php

    include 'code.php';
    
    function sayHello($name)
    {
        echo 'Hello ' . $name;
    }
    
    sayHello($includedName); // Hello Tom
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?