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
https://forums.phpfreaks.com/topic/255762-getters-and-setters-magic-versus-direct/
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.

 

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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.