Sen setter / alıcı yöntemleri olmalıdır. Onlar bir ağrı vardır ama mutlaka bunları kendiniz yazmak zorunda değilsiniz. Bir IDE (örneğin Eclipse ya da NetBeans) sürece sınıf üyesi sağlamak gibi otomatik olarak sizin için bu üretebilir. Ancak, tüm bu uğraşmak istemiyorsanız ve PHP5 konum, eğer sorunu gidermek için onun sihirli yöntem kullanabilirsiniz:
protected $_data=array();
public function __call($method, $args) {
switch (substr($method, 0, 3)) {
case 'get' :
$key = strtolower(substr($method,3));
$data = $this->_data[$key];
return $data;
break;
case 'set' :
$key = strtolower(substr($method,3));
$this->_data[$key] = isset($args[0]) ? $args[0] : null;
return $this;
break;
default :
die("Fatal error: Call to undefined function " . $method);
}
}
Bu kod, bir varolmayan bir yöntem seti ile başlayarak veya almak kullanmak her zaman çalışacaktır. Yani şimdi şöyle / almak (ve dolaylı olarak beyan) değişkenleri ayarlayabilirsiniz:
$object->setName('Bob');
$object->setHairColor('green');
echo $object->getName(); //Outputs Bob
echo $object->getHairColor(); //Outputs Green
No need to declare members or setter/getter functions. If in the future you need to add functionality to a set/get method you simply declare it, essentially overriding the magic method.
Also since the setter method returns $this you can chain them like so:
$object->setName('Bob')
->setHairColor('green')
->setAddress('someplace');
hangi yazmak ve okumak kolay hem de kod için yapar.
The only downside to this approach is that it makes your class structure more difficult to discern. Since you're essentially declaring members and methods on run time, you have to dump the object during execution to see what it contains, rather than reading the class.
If your class needs to declare a clearly defined interface (because it's a library and/or you want phpdoc to generate the API documentation) I'd strongly advice declaring public facing set/get methods along with the above code.