【发布时间】:2021-04-23 16:37:50
【问题描述】:
我有一个带有客户端构造函数的文件 user.php:
class Client{
public $name;
public $pin;
public $balance;
function __construct($name, $pin, $balance){
$this->name = $name;
$this->pin = $pin;
$this->balance = $balance;
}
}
$client1 = new Client("Alan", "0201", 2000);
?>
我还有一个文件,我可以在其中对客户端对象进行一些数学运算:
$balance = $client1->balance;
function withdrow($amount, $balance){
$currentBalance = $balance - $amount;
if($balance < $amount){
echo "You are low on balance";
}
else{
$client1->balance = $currentBalance;
return $currentBalance;
}
}
还有第三个 html 文件,其中我在客户端包含第一个文件,我想在屏幕上回显余额的更新值。但它打印客户端中设置的值。如何更新余额。
我的代码现在看起来像这样,但是 setter 没有改变价值平衡:
class Client{
public $name;
private $pin;
private $balance;
function __construct($name, $pin, $balance){
$this->name = $name;
$this->pin = $pin;
$this->balance = $balance;
}
private function setPin($pin){
$this->pin = $pin;
}
public function getPin(){
return $this->pin;
}
public function setBalance($balance){
$this->balance = $balance;
}
public function getBalance(){
return $this->balance;
}
}
$client1 = new Client("Alan", "0201", 2000);
【问题讨论】:
-
你的客户端类属性必须是私有的并且有setter
-
你能给我举个例子让我尝试设置但没有返回值
-
你可以看到
https://www.tutorialspoint.com/what-are-getters-and-setters-methods-in-php -
你需要编辑你的代码吗?
-
实际上setter没有更新余额我得到相同的结果。我更新了有问题的代码。