如何从类中访问私有变量?

时间:2014-05-18 19:33:41

标签: php

为什么我的函数返回null?

class TestClass2
{
private $test_var="value";

public function getVar(){
    global $test_var;
    return $test_var;
    }
}

$myclass = new TestClass2();

var_dump($myclass::getVar());

是否有其他方法可以访问函数外部的变量,而不是将其作为参数传递,或者将其声明为全局变量?

2 个答案:

答案 0 :(得分:3)

您不需要“全局”,只需要“$ this-> test_var”来访问您的类的方法中的私有变量(在您的情况下,“getVar”方法)。

至于调用该函数,因为它不是静态函数,请使用“ - >”。

class TestClass2
{
  private $test_var="value";

  public function getVar(){
    return $this->test_var;
  }
}

$myclass = new TestClass2();

var_dump($myclass->getVar());

答案 1 :(得分:1)

既然我很确定你在问什么,我会继续给你一个完整的答案。

调用方法时,会向其传递一个名为$this的不可见参数。它是指向您班级的指针。我不确定它是如何在PHP中运行的,但它是C ++如何做到这一点所以行为应该是相似的。

因此,如果你在一个类的方法中并且想要访问它的一个属性,你可以告诉PHP使用全局范围来破坏你的方法并进入类中,但这是笨重的,令人讨厌的,并且可以当你的班级变得更加复杂时,会导致一些并发症。

解决方案是使用PHP神奇地给我们的类的引用。如果您想在$foo->bar内访问$foo->getBar(),可以获得$this->bar。考虑它的好方法是this是一个包含类名称的变量。

这样做的另一个好处是,因为我们在我们的班级,私人财产是可见的。这意味着$this->bar有效,而$foo->bar则不是,假设bar是私有的,当然。

因此,如果我们将此应用于您的代码,那么(通过PHP标准)看起来会变得更加简单和漂亮:

class TestClass2
{
    private $test_var="value";

    public function getVar(){
        return $this->test_var;
    }
}

$myclass = new TestClass2();
$myclass->test_var; // Error
$myclass->getVar(); // Not an error