每次设置PHP对象属性时,我都希望同一对象的另一个属性为该值的20%,或交替放置;设置NetValue时,我想计算另一个属性的20%的增值税。
在C#中,它将类似于:
public class Product
{
public decimal VAT { get; set; }
private decimal _NetValue;
public decimal NetValue { get { return _NetValue; } set { _NetValue = value; this.VAT = (value * 0.2M); } }
}
回到PHP,当我这样做时:
$product = new Product();
$product->NetValue = 10;
echo $product->VAT;
它应该输出:2
。
我如何实现这一目标,因为您只能在PHP中将常量设置为对象属性。是否可以?我看不到类似问题中提到的如何在构造函数中放入任何内容。
尝试使用魔术方法,尤其是__set
和__get
。像这样的东西:
<?php
class Product
{
private $NetValue;
private $VAT;
public function __set($name, $value)
{
if (property_exists($this, $name)) {
if ($name == 'NetValue') {
$this->VAT = 0.2 * $value;
}
$this->$name = $value;
}
}
public function __get($name)
{
if (property_exists($this, $name)) {
return $this->$name;
}
}
}
$product = new Product();
$product->NetValue = 10;
echo($product->VAT);
输出将是:
2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句