2009-06-23 67 views
3

考慮下列情形外生變量的訪問

文件:含./include/functions/table-config.php :

. 
. 
$tablePages = 'orweb_pages'; 
. 
. 

文件:./include/classes/uri-resolve。 PHP 包含:

class URIResolve { 
. 
. 
$category = null ; 
. 
. 
function process_uri() { 
... 
    $this->category = $tablePages; 
... 
} 
. 
. 
}

文件:./settings.php含 :

. 
. 
require_once(ABSPATH.INC.FUNC.'/table-config.php'); 
require_once(ABSPATH.INC.CLASS.'/uri-resolve.php'); 
. 
. 
將這項工作。我的意思是訪問process_uri()中的$ tablePages是可以接受的,還是會給出錯誤的結果。

如果可能發生錯誤,請提出更正或解決方法。

回答

3

使用一個全球性的(不推薦),常量或單配置類。

簡單地包括

$tablePages = 'orweb_pages'; 

會給你的局部變量的範圍,這樣就不會被其他類中可見。如果使用常量:

define('TABLE_PAGES', 'orweb_pages'); 

TABLE_PAGES將可用於整個應用程序的讀取訪問,而不受範圍限制。

一個常量在全局變量上的優點是你不必擔心它在應用程序的其他區域被覆蓋。

+0

做的常量必須是全部大寫還是隻是一種編程習慣,以避免任何常見的標識符衝突? – OrangeRind 2009-06-23 17:08:36

9

使用global keyword

在該文件中,你要指定的值。

global $tablePages; 
$tablePages = 'orweb_pages'; 

而在其他文件中:

class URIResolve { 
    var $category; 
    function process_uri() { 
    global $tablePages; 
    $this->category = $tablePages; 
    } 
} 

而且,所有的全局變量是$GLOBALS陣列中可用(這本身就是一個超全局變量),這樣你就可以在任何地方訪問全局變量,而無需使用全球關鍵字做這樣的事情:

$my_value = $GLOBALS['tablePages']; 

這也有助於更難以無意中覆蓋全球的價值。在前面的示例中,對$tablePages所做的任何更改都會更改全局變量。許多安全漏洞都是由全局的$user創建的,並用更強大的用戶信息覆蓋它。

另外,更安全的方法是提供在構造函數中的變量URIResolve:

class URIResolve { 
    var $category; 

    function __construct ($tablePages) { 
    $this->category= $tablePages; 
    } 

    function process_uri() { 
    // Now you can access table pages here as an variable instance 
    } 
} 

// This would then be used as: 
new URIResolve($tablePages); 
+0

非常感謝! 懷疑:我將不得不手動聲明$ GLOBALS ['tablePages'] ='tablePages';對? – OrangeRind 2009-06-23 17:10:46

+0

我喜歡將最後一個技巧傳遞給構造函數。重要。豎起大拇指。 – andho 2012-02-29 05:10:49

0
<?php 
//Use variable php : $GLOBALS in __construct 
$x = "Example variable outer class"; 

class ExampleClass{ 
    public $variables; 
    function __construct() 
    { 
    $this->variables = $GLOBALS; //get all variables from $GLOBALS 
    } 
    // example get value var 
    public function UseVar(){ 
    echo $this->variables['x']; // return Example variable outer class 
    } 
    // example set value var 
    public function setVar(){ 
    $this->variables['x'] = 100; 
    } 
} 
echo $x // return Example variable outer class; 

$Example = new ExampleClass(); 
$Example->UseVar(); // return Example variable outer class 
$Example->setVar(); // $x = 100; 

// or use attr variables 
echo $Example->variables['x']; // 100 
$Example->variables['x'] = "Hiii"; 
?>