我有一个简单的代码示例,我想设置私有属性$ 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;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
这会导致我无法访问私有属性$ ttlBal的错误.我可以通过哪种方式访问它.
您应该为您的类添加一个公共setter方法:
class Foo {
private $var;
public function setVar($value) {
$this->var = $value;
}
}
Run Code Online (Sandbox Code Playgroud)
在许多情况下,protected如果您使用,也是您想要的private.如果您只想将变量隐藏在公共访问中,请使用protected.
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |