2010-12-07 34 views
8

如何在此類中設置全局變量?我曾經嘗試這樣做:PHP類中的變量範圍

class myClass 
{ 
    $test = "The Test Worked!"; 
    function example() 
    { 
     echo $test; 
    } 
    function example2() 
    { 
     echo $test." again"; 
    } 
} 

它未能加載頁面完全引用一個500錯誤。接下來,我想這一個:

class myClass 
{ 
    public $test = "The Test Worked!"; 
    function example() 
    { 
     echo $test; 
    } 
    function example2() 
    { 
     echo $test." again"; 
    } 
} 

但是當我印這兩個,我看到的是「再次」對不起,這麼簡單的問題!

謝謝!

回答

17

這個變量能夠像這樣

echo $this->test; 
+0

謝謝它例題工作 – 2010-12-07 03:30:55

1

嘗試增加$this您變量的前訪問;你可以改變第二個例子

class myClass { 
    public $test = "The Test Worked!"; 

    function example() { 
     echo $this->test; 
    } 

    function example2(){ 
     echo $this->test." again"; 
    } 
} 
5
class Foo { 

    public $bar = 'bar'; 

    function baz() { 
     $bar; // refers to local variable inside function, currently undefined 

     $this->bar; // refers to property $bar of $this object, 
        // i.e. the value 'bar' 
    } 
} 

$foo = new Foo(); 
$foo->bar; // refers to property $bar of object $foo, i.e. the value 'bar' 

請開始閱讀這裏:http://php.net/manual/en/language.oop5.basic.php

3

實際上有兩種方法可以從任一類的內部或外部訪問它在一個類中的變量或函數,如果他們要求的項目是公開的(或保護某些情況下)

​​
+0

那裏,沒有按」它需要回聲$ this->測試。「再次」;? – 2010-12-07 03:51:15

7

如果你想要一個實例變量(只保存爲類的該實例),用途:

$this->test 

(作爲另一個答案建議。)

如果你想要一個「類」變量,像這樣的「靜態」關鍵字的前綴是:

類變量大於實例不同因爲從該類創建的所有對象實例都將共享相同的變量。

(注意要訪問類變量,使用類名稱,或「自我」,然後「::」)如果你想有一個真正的常數(不變)中,使用「常量」

class myClass 
{ 
    public static $test = "The Test Worked!"; 
    function example() 
    { 
     echo self::$test; 
    } 
    function example2() 
    { 
     echo self::$test." again"; 
    } 
} 

最後前(再次與「自我」加「::」加上常量的名稱訪問它(雖然此時忽略「$」):!

class myClass 
{ 
    const test = "The Test Worked!"; 
    function example() 
    { 
     echo self::test; 
    } 
    function example2() 
    { 
     echo self::test." again"; 
    } 
}