$$ for classes variables?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jaceinla
Forum Commoner
Posts: 25
Joined: Thu Oct 14, 2010 12:57 pm

$$ for classes variables?

Post by jaceinla »

Hi all, I'm aware that:

Code: Select all

$dog = "cat";
$cat = "dog";

echo $$dog; will echo out "dog"
Can this be done with class variables?

Code: Select all

protected cat;
protected dog;

public function __construct() {
    $this->cat = "dog";
    $this-dog = "cat";
}

public function echoOut() {
    $this->this->dog;    //does not work
}

Why am I asking? I'm getting an image height and width, I need to find the bigger of the two, so I have $this->bigger and $this->smaller which either equal "height" or "width" so that when I use these variables, I'm using them as follows:

Code: Select all

$this->ratio = $this->bigger/$this->smaller;   //bigger and smaller are strings that refer to already set variables $this->height, $this->width
Thanks in advanced!

PS. I know I can do an if statement to get the ratio once and keep going, but this option is a little cleaner and flexible.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: $$ for classes variables?

Post by Weirdan »

Code: Select all

echo $this->{$this->bigger};
jaceinla
Forum Commoner
Posts: 25
Joined: Thu Oct 14, 2010 12:57 pm

Re: $$ for classes variables?

Post by jaceinla »

Thank you!
Post Reply