【问题标题】:How to update value in a class objecct in php如何在php中更新类对象中的值
【发布时间】: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没有更新余额我得到相同的结果。我更新了有问题的代码。

标签: php oop


【解决方案1】:

您必须通过引用调用来调用函数

function withdrow($amount, &$balance){ /** call by reference */ 
   $currentBalance = $balance - $amount;
   if($balance < $amount){
       echo "You are low on balance";
   }
   else{
       $client1->balance = $currentBalance;
       return $currentBalance;
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 2019-04-01
    • 2021-07-17
    相关资源
    最近更新 更多