Senki Sem
Senki Sem

Reputation: 131

How do I access a private variable from a class?

Why does my function return null?

class TestClass2
{
private $test_var="value";

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

$myclass = new TestClass2();

var_dump($myclass::getVar());

Is there an other way to access variables, which are outside the function, other than passing it in as a parameter, or declaring it as global?

Upvotes: 0

Views: 105

Answers (2)

Meredith
Meredith

Reputation: 840

Now that I'm pretty certain what you're asking, I'll go ahead and give you a full answer.

When you call a method, an invisible argument, called $this is passed to it. It is a pointer to your class. I'm not certain this is how it works in PHP, but it's how C++ does it so the behaviors should be similar.

So if you're inside a class's method and you want to access one of its properties, you could tell PHP to use the global scope to break outside of your method and into the class, but that's bulky, obnoxious, and can lead to some complications as your class gets more complex.

The solution is to use the reference to our class that PHP magically gives us. If you want to access $foo->bar inside $foo->getBar(), you can get $this->bar. A good way to think of it is that this is a variable that holds the name of your class.

An additional advantage of this is that, because we're in our class, private properties are visible. This means that $this->bar is valid, whereas $foo->bar isn't, assuming bar is private, of course.

So if we apply this to your code, it becomes a lot simpler and prettier to look at (by PHP standards):

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

Upvotes: 1

Bogdan
Bogdan

Reputation: 397

You do not need "global", you just need "$this->test_var" to access your private variable inside a method of your class (in your case, the "getVar" method).

As for calling the function, since it is not static, use "->".

class TestClass2
{
  private $test_var="value";

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

$myclass = new TestClass2();

var_dump($myclass->getVar());

Upvotes: 3

Related Questions