Reputation: 109
I have a simple example of code in which i would like to set the private property $ttlBal.
<$php
$balance = new Customer;
$greeting = fopen("greeting.txt", "r");
while(!feof($greeting)){
echo fgets($greeting) . "<br>";
}
fclose($greeting);
$balance->acctBal = 12;
$balance->deposits = 12;
$balance->fdr = 12;
$balance->findAvail($balance->acctBal, $balance->deposits, $balance->ttlBal);
class Customer{
public $acctBal;
public $deposits;
private $acctAvail;
private $ttlBal;
public $fdr;
public function findAvail($bal, $dep, $ttlBal){
echo $this->ttlBal = $bal - $dep;
}
}
?>
This brings about an error that I cannot access the private property $ttlBal. In which way can I access this.
Upvotes: 1
Views: 56
Reputation: 3000
Youe error is here $balance->ttlBal
Either you will make the property public
or you would implement get()
and set()
methods for it in Customer
class.
As an example
public function get_ttlBal()
{
return $this->ttlBal;
}
and then you can call
$balance->findAvail($balance->acctBal, $balance->deposits, $balance->get_ttlBal());
Upvotes: 1
Reputation: 157947
You should add a public setter method to your class:
class Foo {
private $var;
public function setVar($value) {
$this->var = $value;
}
}
Also in many cases protected
is what you want if you use private
. If you just want to hide the variable from public access, use protected
.
Upvotes: 6