Pain Posted May 27, 2013 Share Posted May 27, 2013 Im having trouble understanding the point of assigning certain values to certain variables within the class. Say we have <?php class MyClass { public $variable; public function getVariable($variable) { $this->variable = $variable; } } Why assign the value of $variable to $this->variable instead of simply using $variable which has been passed as an argument? Thanks:) Quote Link to comment https://forums.phpfreaks.com/topic/278445-this-variable-variable-why-assign/ Share on other sites More sharing options...
Jessica Posted May 27, 2013 Share Posted May 27, 2013 To use it later. I suggest you do some reading on OOP. Find a book and go through it. Quote Link to comment https://forums.phpfreaks.com/topic/278445-this-variable-variable-why-assign/#findComment-1432588 Share on other sites More sharing options...
Barand Posted May 27, 2013 Share Posted May 27, 2013 $variable is available only inside that method, Read up on variable scope. $this->variable is available to other methods throughout the class, and (as it declared public) to other classes. Quote Link to comment https://forums.phpfreaks.com/topic/278445-this-variable-variable-why-assign/#findComment-1432589 Share on other sites More sharing options...
Psycho Posted May 27, 2013 Share Posted May 27, 2013 I'll also add that the sample method you created above should be called setVariable(). A get method should be used to retrieve a propert - not set one. Quote Link to comment https://forums.phpfreaks.com/topic/278445-this-variable-variable-why-assign/#findComment-1432594 Share on other sites More sharing options...
DHood Posted May 28, 2013 Share Posted May 28, 2013 class MyClass { public $variable; public function setVariable($value) { $this->variable = $value; } public function getVariable($variable) { var_dump($this->variable); var_dump($variable); } } $test = new MyClass; $test->setVariable('test'); $test->getVariable(); Using setVariable like Psycho suggested, you'll see why you need to assign it to $this. Quote Link to comment https://forums.phpfreaks.com/topic/278445-this-variable-variable-why-assign/#findComment-1432731 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.