Sachin
Sachin

Reputation: 1698

Can I use a variable without $this in PHP class methods?

I am wondering whether is it possible to use a variable without $this in PHP class methods. So can we declare and initialize a variable (aka property in OOP) without using $this?

Example

public function set_variable()
{
    $var = "some value";
    return $var;
}

OR

public function set_variable()
{
    $this->var = "some value";
    return $this->var;
}

So which one is correct and more useful? I know we CAN'T access a variable from some other method in a class if we have not preciously declared it with $this.

But what if we don't need to access it outside of a method in which we have declared it? Then, I think one can simply use it without $this. What do you think?

Upvotes: 1

Views: 897

Answers (1)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

If you declare a variable inside the class method and that is for just internal use (e.g to hold a value inside the function), and you just want to return the value to the calling function, the following approach is correct:

public function set_variable()
{
    $var = "some value";  // $var will not be available outside the function.
    return $var;
}

If you have some global variable declared and you want to alter or set any value to it inside a function, you can use the 2nd approach you mentioned:

class Demo{
    protected $var = '';
    public function set_variable()
    {
        $this->var = "some value";
        return $this->var;  // Here this function will return new value of the global variable `var`
    }
}

Upvotes: 3

Related Questions