我可以从类外部更改类中定义的函数或变量,但不使用全局变量吗?

这是包含文件 #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()
...

最佳答案

你问的是 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;

关于PHP - 从类外部更改类变量/函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4955287/

10-09 03:13