2008-07-25, 02:43 AM
Hi All.
I was reading a tutorial that explain the __get an __set methods in class
inside this tutorial the author used this sentece throw new Exception
and he did explain all the code except this one.
I tried to google it but I didn't get any simple explation for it using class.
here is the code used in the tutorial maybe that help you to help me understand it.
I was reading a tutorial that explain the __get an __set methods in class
inside this tutorial the author used this sentece throw new Exception
and he did explain all the code except this one.
I tried to google it but I didn't get any simple explation for it using class.
here is the code used in the tutorial maybe that help you to help me understand it.
<?php
class PropertyObject {
private $_properties = array(
'name' => null,
'dateofbirth' => null
);
function __get($propertyName) {
if(!array_key_exists($propertyName, $this->_properties))
throw new Exception('Invalid property value!');
if(method_exists($this, 'get' . $propertyName)) {
return call_user_func(array($this, 'get' . $propertyName));
} else {
return $this->_properties[$propertyName];
}
}
function __set($propertyName, $value) {
if(!array_key_exists($propertyName, $this->_properties))
throw new Exception('Invalid property value!');
if(method_exists ($this, 'set' . $propertyName)) {
return call_User_func(
array($this, 'set'.$propertyName),
$value
);
} else {
$this->_properties[$propertyName] = $value;
}
}
function setDateOfBirth($dob) {
if(strtotime($dob) == -1) {
throw new Exception ("The date of birth must be a valid date!");
}
$this->_properties['dateofbirth'] = $dob;
}
function sayHello() {
//$this->_properties['name'] and $this->_properties['dateofbirth']
//will be retrieved by __get
print "Hi! My name is $this->name. I was born on $this->dateofbirth";
}
}
$obj = new PropertyObject();
$obj->name = 'Bob'; //"Bob" is assigned to $_properties['name'] by __set
$obj->dateofbirth = 'March 5, l977'; //setDatoOfBirth is invoked by __set
$obj->sayHello();
$obj->dateofbirth = 'blue'; //throws an exception
?>