将变量传递到类函数中并使用它


passing variable into class functions and use it

我有一个类,我正试图在我的网站上实现它,但我无法将变量传递到它…

class Order {
   var $totalPrice = null;
   function load() {
      $this->totalPrice = 123;
   }
   function loadByPaymentSessionId($paymentSessionId) {
       $this->totalPrice = 123;
   }
}
$order = new Order();
$order->load();

如何在类外设置$this->totalPrice?

目前您的房产已被授予公共访问权限,因此:

$order->totalPrice = 4.65;

或者,如果你想在实例化时设置价格,你可以为构造函数提供一个参数:

class Order {
    public $totalPrice;
    public function __construct($totalPrice = null)
    {
        $this->totalPrice = $totalPrice;
    }
}
$order = new Order(4.85);

或者,如果在设置值时需要执行某种逻辑,则可以阻止对类成员的直接访问,并提供一个访问器方法:

class Order {
    private $totalPrice;
    public function setTotalPrice($totalPrice)
    {  
        $this->totalPrice = (float) $totalPrice;
    }
}

这个想法是将$totalPrice设为私有,并通过以下函数设置:

function load2($newVal) {
      //some validation
      $this->totalPrice = $newVal;
   }