Reputation: 13
I'm trying to learn object oriented PHP by porting some of the simple exercises I've learnt in Java to PHP. This is one of them, to calculate the total salary of 3 people.
I'm apparently having a problem with the array in the family class - php gives an error about "Undefined variable: a_family" on line 32. Could anybody point me in the correct direction?
<?php
class person {
private $name;
private $salary;
//constructor
function __construct($given_name, $given_salary) {
$this->name = $given_name;
$this->salary = $given_salary;
}
//getter for salary
function get_salary() {
return $this->salary;
}
}
class family {
private $a_family;
function __construct() {
$a_family = array();
}
function add_family_member($given_person) {
$a_family[] = $given_person;
}
function get_total_salary() {
$total_salary = 0;
foreach ($a_family as $member) {
$total_salary = $total_salary + $member->get_salary();
}
return $total_salary;
}
}
$mum = new person("Mummy", 500);
$dad = new person("Daddy", 1500);
$sis = new person("Sister", 20);
$my_family = new family();
$my_family->add_family_member($mum);
$my_family->add_family_member($dad);
$my_family->add_family_member($sis);
$family_income = $my_family->get_total_salary();
?>
<!-- start HTML -->
<html>
<head>
</head>
<body>
<p>My total family income is $<?php echo $family_income; ?>.</p>
</body>
</html>
Upvotes: 1
Views: 120
Reputation: 162831
Unlike java, in PHP the this
keyword is mandatory for referencing instance variables even when there is no ambiguity. You've done it correctly in your person class. You need to use this
in your family class too.
$this->a_family = array();
...
$this->a_family[] = $given_person;
...
foreach ($this->a_family as $member) {
...
Upvotes: 1
Reputation: 43619
You need:
$this->a_family
because you a referring to a variable in the class scope, even if you have set $a_family
to private
.
$a_family
only refers to the variable in the current method.
Upvotes: 1
Reputation: 7215
You need to be referencing $a_family as $this->a_family instead within your functions.
Upvotes: 1
Reputation: 625217
You want:
$this->a_family = array();
and:
$this->a_family[] = $given_person;
just like you've done in the first class.
Upvotes: 2