对于处理类之间的变量感到困惑

时间:2012-10-22 13:34:53

标签: php class variables

我有一个这样的课程:

class sqlClass    {
  var $myvar = "test value 1"
  public function test01() {
    global $myvar;
    //some operations here
    $myvar = "test value 2"
    return true;
  }
}

在其他文件中我有这个PHP脚本:

include_once('functions.php'); // where my class is
$data = new sqlClass();
if ($data->test01()) {
  echo $data->myvar;
} else { echo "No value"; }

在这个示例中,test01()总是正确的,所以我保证$myvar更改,但是,当我在所谓的类中执行函数后打印$myvar时要更改它的值,它会打印旧值“test value 1”而不是“test value 2”。那么,我错过了什么?

2 个答案:

答案 0 :(得分:4)

好的,首先你不应该使用var关键字。这是你不应该使用的php4,除非你维护一个遗留应用程序。相反,您使用the visibility keywords - public,protected, or private之一。

其次你不应该在一个类中使用global而不应该有需要。要访问使用$this->memberName的类成员,如果需要访问类外部的变量,则应将这些变量作为参数传递给方法或构造函数。

所以这就是你的代码应该是这样的:

class sqlClass    {
  public $myvar = "test value 1";

  public function test01() {

    //some operations here
    $this->myvar = "test value 2"

    return true;
  }
}

说过我会阅读OOP in the manual for php5

上的整个部分

答案 1 :(得分:0)

要更改对象的实例变量,请使用$this->

class sqlClass {

    public $myvar = "test value 1"

    public function test01() {
      $this->myvar = "test value 2"
      return true;
    }

}

这会改变变量$data->myvar。您使用global执行的操作意味着它正在更改使用myvar输出的全局变量echo $myvar。它与对象$data无关。

相关问题