Simple example of a class in PHP

A simple example of a class in PHP
<?php # person

class person {

public function __construct( $name, $age, $height, $weight )
{
$this->name   = $name;
$this->age    = $age;
$this->height = $height;
$this->weight = $weight;
}

// functions that return information

public function get_name()
{
return $this->name;
}

public function get_age()
{
return $this->age;
}

public function get_height()
{
return $this->height;
}

public function get_weight()
{
return $this->weight();
}

// functions that change the object.

public function change_name( $name )
{
$this->name = $name;
}

public function add_weight( $weight )
{
$this->weight = $this->weight + $weight;
}

public function lose_weight( $weight )
{
$this->weight = $this->weight – $weight;
}

}

//Initialise a person
$paul = new person(‘Paul Gibbs’, 17, ‘6\’1″‘, 210);

$john = new person(‘John Smith’, 36, ‘5\”, 160);

echo(“<br/>”);

print_r($paul);

echo(“<br/>”);

echo(“Loose 10 pounds from this person<br/>”);

$paul->lose_weight(10);

echo(“<br/>”);

print_r($paul);

echo(“<br/>”);

//A possible use :

$people = array($paul, $john);   //Create an array of people

foreach( $people as $person ) {
echo “This persons name is ” . $person->get_name() . “<br/>”;
echo “This person is “.$person->get_age().” years old.<br/>”;
}

class employee extends person {

public function __construct($name, $age, $height, $weight, $salary, $startdate)
{
parent::__construct($name, $age, $height, $weight);

$this->salary = $salary;
$this->startdate = $startdate;

}

public function get_salary()
{
return $this->salary;
}

public function get_startdate()
{
return $this->startdate;
}

}

$pete = new employee(‘Pete Coles’, 22, ‘6’, 200, 20000, 2012-06-04);

echo(“<br/>”);

print_r($pete);

?>

Leave a Reply