Om du skriver korrekta kommentarer och lägger till det kommatecken som saknas så ser det ut att fungera.
Kod:
<?php
class Person
{
private $firstname;
private $lastname;
public function __construct($pFirstname, $pLastname)
{
$this->firstname = $pFirstname;
$this->lastname = $pLastname;
}
public function __set($name, $value)
{
switch ($name)
{
case 'firstname':
$this->firstname = $value;
break;
case 'lastname':
$this->lastname = $value;
break;
default:
# By throwing Exception for undefined property we can enforce strict property definition rules
# we also achive better error messages for improved debugging during development
# this is necessare because of lack of support for strict properties in php 5.3.15
$error = "Error: __set property: " . $name . " not supported by class: " . __CLASS__ ;
throw new Exception($error);
break;
}
}
public function __get($name)
{
switch ($name)
{
case 'firstname':
return $this->firstname;
break;
case 'lastname':
return $this->lastname;
break;
default:
# By throwing Exception for undefined property we can enforce strict property definition rules
# we also achive better error messages for improved debugging during development
# this is necessare because of lack of support for strict properties in php 5.3.15
$error = "Error: __get property: " . $name . " not supported by class: " . __CLASS__ ;
throw new Exception($error);
break;
}
return null;
}
/*
* a String representation for all Persons.
*/
public function __toString()
{
return "Firstname: $this->firstname , Lastname: $this->lastname";
}
}
?>
<?php
try
{
# create a PHP Array and initialize it with Person objects
$persons = array
(
new Person("Fredrik", "Framberg"),
new Person("Greta", "Gavelstam"),
new Person("Urban", "Urberg"),
new Person("Anna", "Ambtesteg"),
new Person("Henrik", "Hammarberg"),
new Person("Kristina", "Karlestam"),
new Person("Hans", "Hallin"),
new Person("Berit", "Bygd‚n")
);
# print out the results - calls Person->__toString().
foreach($persons as $person) echo "$person<br>\n";
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>