2011-02-10 47 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; 
    } 
}