2011-06-13 77 views
-2

可能重複:
To pass value of a variable in one function to another function in same class使用全局變量

在一個函數變量的值在其他功能提供在PHP中使用「全球」同一類。如果是這樣,請建議如何使用Global進行實現。

+2

你有沒有再問同樣的問題? http://stackoverflow.com/questions/6289352/to-pass-value-of-a-variable-in-one-function-to-another-function-in-same-class – afarazit 2011-06-13 01:03:15

+0

全球?在同一班級的另一個功能?私人類變量有什麼問題? – hakre 2011-06-13 01:03:33

+0

實際上,第一個函數中使用的變量的值是傳遞給第一個函數的參數。我想這是可用的第二個功能,是否有可能通過使用GLOBAL – dhaam 2011-06-13 01:06:25

回答

5

如果您位於對象內,則不需要創建變量GLOBAL。

class myClass { 

    public $myVar = "Hello"; 

    function myFunction() { 
    echo $this->$myVar; 
    } 

} 

這是對象的要點之一 - 您可以爲變量賦值不同的值,並在不同的方法中獲取/設置這些變量。此外,您可以創建多個對象實例,每個對象都擁有相同結構內的不同信息並使用相同的方法。

+0

+1對於實際回答問題。雖然實際上這個解決方案的行爲不像_global_,因爲非靜態屬性會在類的不同實例間發生變化。 – Tadeck 2011-06-13 01:27:20

0

是的,一個函數中的變量值可以在同一個類的另一個函數中使用「GLOBAL」提供。下面的代碼打印3

class Foo 
{ 
    public function f1($arg) { 
    GLOBAL $x; 
    $x = $arg; 
    } 
    public function f2() { 
    GLOBAL $x; 
    return $x; 
    } 
} 

$foo = new Foo; 
$foo->f1(3); 
echo $foo->f2(); 

然而,全局變量的使用通常是設計不良的標誌。

請注意,雖然PHP中的關鍵字不區分大小寫,但它們是自定義的小寫字母。不僅如此,包含所有全局變量的超全局數組稱爲$GLOBALS,而不是GLOBAL

+0

讓我試試吧奧斯瓦爾德,謝謝 – dhaam 2011-06-13 01:14:59

+0

使用全球也無法實現 – dhaam 2011-06-13 01:31:31

2

此外什麼@Codecraft說(關於使用公共屬性),你可以使用:

  • 確實全局變量(這是真正的東西,你應該避免這樣做),在參數
  • 傳遞值,
  • 類中
  • 靜態變量,

下面是一個使用靜態變量(私營),因爲我覺得THI的例子西服您的需求最好的:

class MyClass { 
    private static $_something; 
    public function write() { 
     static::$_something = 'ok'; 
    } 
    public function read() { 
     return static::$_something; 
    } 
} 

$x = new MyClass(); 
$x->write(); 
var_dump($x->read()); 

,輸出:

字符串(2) 「OK」

這其實是像一個全球性的,但只能從(因爲關鍵字「私人」)和常見的實例t他班。如果你使用設置一些非靜態屬性,它會改變類的不同實例(一個對象可能有不同的值存儲在它比其他對象有)。基於靜態和非靜態變量的解決方案的

比較:基於

解決方案靜態變量會給你真的全球類似的行爲(在不同的情況下,通過同一個類的值) :

class MyClass { 
    private static $_something; 
    public function write() { 
     static::$_something = 'ok'; 
    } 
    public function read() { 
     return static::$_something; 
    } 
} 

// first instance 
$x = new MyClass(); 
$x->write(); 
// second instance 
$y = new MyClass(); 
var_dump($y->read()); 

,其輸出:

字符串(2) 「OK」

而基於非靜態變量的解決方案看起來像:

class MyClass { 
    private $_something; 
    public function write() { 
     $this->_something = 'ok'; 
    } 
    public function read() { 
     return $this->_something; 
    } 
} 

// first instance 
$x = new MyClass(); 
$x->write(); 
// second instance 
$y = new MyClass(); 
var_dump($y->read()); 

而是將輸出:

NULL

這意味着在這種情況下,第二個實例沒有爲變量分配值,您想表現得像「全局」。