2013-06-05 67 views
-1

所以我有3個文件包括PHP變量的作用域

file1.php

$var = "string"; 

file2.php

include(file1.php); 
include(file3.php); 
echo $var; 
$test = new test(); 

file3.php

class test 
{ 
    public function __construct() 
    { 
    if($var = "string") 
    { 
     // do things 
    } 
    } 
    } 

現在,在文件2中的回聲工作正常 豪ver,在測試類中,變量返回一個Notice:Undefined變量: 我試過將$ var更改爲全局變量,但這似乎沒有幫助。我想我不能正確理解包含文件的範圍。任何人都可以幫助我,所以我可以在課堂上使用$ var!

感謝

+3

製作吧'global'在構造函數中會有所幫助,但它會被_better_通過'$ var'到'__construct()'在'公共職能__construct ($ VAR){}' –

回答

1

有兩種方法可以做到這一點

錯誤的方式

class test 
{ 
    public function __construct() 
    { 
     global $var; 
     if($var == "string") 
     { 
      // do things 
     } 
    } 
} 

這將導入VAR到constuctors範圍,但違反了這是面向對象編程的最大的好處封裝功能。

這是正確的方式

class test 
{ 
    public function __construct($var) 
    { 
     if($var == "string") 
     { 
      // do things 
     } 
    } 
} 

$test = new test($var);