2011-02-10 18 views
4

我可以在類之外更改在類中定義的函數或變量,但不使用全局變量嗎?PHP - 從類之外更改類變量/函數

這是類,裏面包含文件#2:

class moo{ 
    function whatever(){ 
    $somestuff = "...."; 
    return $somestuff; // <- is it possible to change this from "include file #1" 
    } 
} 
在主應用程序

,這是怎樣的類用於:

include "file1.php"; 
include "file2.php"; // <- this is where the class above is defined 

$what = $moo::whatever() 
... 
+0

你是什麼意思的「包含文件#1」? – Gordon 2011-02-10 09:27:28

回答

6

你是問關於getter和setter或Static variables

class moo{ 

    // Declare class variable 
    public $somestuff = false; 

    // Declare static class variable, this will be the same for all class 
    // instances 
    public static $myStatic = false; 

    // Setter for class variable 
    function setSomething($s) 
    { 
     $this->somestuff = $s; 
     return true; 
    } 

    // Getter for class variable 
    function getSomething($s) 
    { 
     return $this->somestuff; 
    } 
} 

moo::$myStatic = "Bar"; 

$moo = new moo(); 
$moo->setSomething("Foo"); 
// This will echo "Foo"; 
echo $moo->getSomething(); 

// This will echo "Bar" 
echo moo::$myStatic; 

// So will this 
echo $moo::$myStatic; 
1

將其設置爲在實例屬性構造函數,然後讓方法返回屬性中的任何值。這樣,您可以在任何可以獲取對它們的引用的地方更改不同實例上的值。

3

有幾種可能性,以實現自己的目標。你可以在你的類中編寫一個getMethod和一個setMethod來設置和獲取變量。

class moo{ 

    public $somestuff = 'abcdefg'; 

    function setSomestuff (value) { 
    $this->somestuff = value; 
    } 

    function getSomestuff() { 
    return $this->somestuff; 
    } 
}