return in OOP
Hi,
Code below is just to print a message. Nothing more. Question is: Whether we have the line return $this->myname; or not, it works fine but why some people still use return in such cases? Is it just a matter of taste or I'm missing something about OOP? Example below might look silly but I just wanted to explain what I meant.
Thanks in advance
class Whatever
{
var myname = null;
private function set_my_name($name)
{
$this->myname = $name;
return $this->myname;
}
public function say_hello($name)
{
$this->set_my_name($name);
echo 'Hello ' . $this->myname;
}
}
$obj = new Whatever();
$obj->say_hello('John');
Related Article: Php oop question
is a PHP discussion thread by emily-bcot that has 4 replies, was last updated 1 year ago and has been tagged with the keywords: oop, php.
veledrom
Practically a Posting Shark
822 posts since Apr 2008
Reputation Points: 42
Solved Threads: 1
Skill Endorsements: 0
Sorry, misread your post :(
diafol
Keep Smiling
10,839 posts since Oct 2006
Reputation Points: 1,675
Solved Threads: 1,536
Skill Endorsements: 61
You could use return statement to return true on success and false on failure. This way you can test the method when calling it from somewhere else like:
$we = new Whatever;
if($we->say_hello('Jack')) {
// do something like log success
// ...
} else {
// do something else like log failure
// ...
}
The say_hello() function can be changed to:
public function say_hello($name)
{
if($name != '')
{
$this->set_my_name($name);
echo 'Hello ' . $this->myname;
return true;
} else {
return false;
}
}
Maybe not the best example but you get the idea. Returning anything is not mandatory of course.
broj1
Nearly a Posting Virtuoso
1,216 posts since Jan 2011
Reputation Points: 167
Solved Threads: 165
Skill Endorsements: 13
Seing people using return $this->myname part was making me think that it was a kind of "COMMIT" statement like we have have in DB queries. If the line $this->myname = $name; sets and reflects the changes instantly then there is no point of using return $this->myname. Just an extra unnecessary line.
veledrom
Practically a Posting Shark
822 posts since Apr 2008
Reputation Points: 42
Solved Threads: 1
Skill Endorsements: 0