我可以从类外部更改类中定义的函数或变量,但不使用全局变量吗?
这是类,内部包含文件#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 :(得分:7)
您是在询问Getters and Setters还是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;
}
}
答案 2 :(得分:1)
在构造函数中将其设置为实例属性,然后让方法返回属性中的任何值。这样,您可以在任何可以获得对它们的引用的地方更改不同实例的值。