Prev | Current Page 243 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

An example follows:
class Employee
{
var $name;
function __set($propName, $propValue)
{
echo "Nonexistent variable: \$$propName!";
}
}
$employee = new Employee ();
$employee->name = "Mario";
$employee->title = "Executive Chef";
This results in the following output:
Nonexistent variable: $title!
Of course, you could use this method to actually extend the class with new properties,
like this:
174 CHAPTER 6 ?–  O BJECT-ORIENTED PHP
class Employee
{
var $name;
function __set($propName, $propValue)
{
$this->$propName = $propValue;
}
}
$employee = new Employee();
$employee->name = "Mario";
$employee->title = "Executive Chef";
echo "Name: ".$employee->name;
echo "
";
echo "Title: ".$employee->title;
This produces the following:
Name: Mario
Title: Executive Chef
Getting Properties
The accessor, or mutator method, is responsible for encapsulating the code required
for retrieving a class variable. Its prototype follows:
boolean __get([string property name])
It takes as input one parameter, the name of the property whose value you??™d like to
retrieve. It should return the value TRUE on successful execution, and FALSE otherwise.
An example follows:
class Employee
{
var $name;
var $city;
protected $wage;
CHAPTER 6 ?–  O BJECT-ORIENTED PHP 175
function __get($propName)
{
echo "__get called!
";
$vars = array("name","city");
if (in_array($propName, $vars))
{
return $this->$propName;
} else {
return "No such variable!";
}
}
}
$employee = new Employee();
$employee->name = "Mario";
echo $employee->name.


Pages:
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255