2

I am having trouble understanding when and why you need to use $this->$property. So adding the $ to both the the this keyword and the property. I have only seen this used within the magic methods __get() and __set(). Can anybody elaborate?

1
  • 2
    Maybe when the property name is saved in a variable (e.g. $var = "ThisIsMyProperty";) then you use it like this: $this->$var ?! Commented May 30, 2015 at 22:20

1 Answer 1

4

You can use $this->$property when $property contains a name of a property or $this->$function() when $function contains a function name.

Example:

class MyClass {
    private $email = "[email protected]";

    public function getProperty($p){
        return $this->$p;
    }
}

$obj = new MyClass;
$obj->getProperty("email"); // Returns [email protected]
Sign up to request clarification or add additional context in comments.

3 Comments

Agree with @Richard Reiber
Ahh I see. So referencing the property/method? Thank you sir.
@JuanRangel: Yes. No problem. You can also see the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.