Jump to content

Getters and Setters - magic versus direct


scanreg

Recommended Posts

I know that magic __get and __set are invoked automatically when an object is instantiated, but what about stuff like getName() and setName()

 

class NameClass {
private $_name;
public function getName() {	
return $this->_name;
    }
public function setName($value) {
$this->_name = $value;
    }
}

$someName = new NameClass();
$someName->setName('Bob'); 
echo $someName->getName(); 

 

1. Could the setName() and getName() just as easily be named something generic like:

 

hotName()

coldName()

 

class NameClass {
private $_name;
public function hotName() {	
return $this->_name;
    }
public function coldName($value) {
$this->_name = $value;
    }
}

$someName = new NameClass();
$someName->coldName('Bob'); 
echo $someName->hotName(); 

 

2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct?

 

Thanks :)

 

 

Link to comment
Share on other sites

1. Could the setName() and getName() just as easily be named something generic like:

 

hotName()

coldName()

They can be named anything you want. They are simply methods in a class.

 

2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct?

 

Yes and no. With the code you provided they won't do anything without being called manually. However, you could call them from magic methods (like __get and __set) if you wanted to.

Link to comment
Share on other sites

 

Yes and no. With the code you provided they won't do anything without being called manually. However, you could call them from magic methods (like __get and __set) if you wanted to.

 

Gotcha, if within the magic methods the regular methods could be called but otherwise they need to be called directly

 

Thanks :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.