Marcus, I agree there should be more debate. __get/__set does have consequences and gotchas.
For example, Here is another implementation to look at
PHP Code:
<?php
interface Properties {
public function __get($property);
public function __set($property, $value);
public function __isset($property);
public function __unset($property);
}
class AccessorPropertySupport implements Properties {
public function __get($property) {
if (method_exists($this, 'get' . $property)) {
$method = 'get' . $property;
return $this->$method();
} else {
$internalProperty = '_' . $property;
return $this->$internalProperty;
}
}
public function __set($property, $value) {
if (method_exists($this, 'set' . $property)) {
$method = 'set' . $property;
$this->$method($value);
} else {
$internalProperty = '_' . $property;
$this->$internalProperty = $value;
}
}
public function __isset($property) {
if (method_exists($this, 'get' . $property)) {
return TRUE;
} else {
$internalProperty = '_' . $property;
return isset($this->$internalProperty);
}
}
public function __unset($property) {
throw new Exception('Cannot remove properties.');
}
}
class Rectangle extends AccessorPropertySupport {
protected $_width;
protected $_length;
function __construct($width, $length) {
$this->width = $width;
$this->length = $length;
}
function getArea() {
return $this->_width * $this->_length;
// We cannot use the same notation from within the class as
// we do externally to the class because our magic method
// does not get called internally.
// return $this->width * $this->length
// does not work here.
}
}
$rec =& new Rectangle(10, 20);
echo 'width:', $rec->width, "<BR>\n";
echo 'length:', $rec->length, "<BR>\n";
echo 'area:', $rec->area, "<BR>\n";
?>
Bookmarks