如何将属性从一种方法传递到另一种方法?

时间:2018-01-25 23:10:15

标签: php

我正在努力理解我想要完成的概念,我甚至不知道它叫什么,所以请耐心等待。我只能告诉你我想要完成的事情。

我正在创建一个将测量值从一个转换为另一个的类。

class UnitConverter {

    public $value;

    /**
    * Amount to convert
    */
    public function convert($value){
        $this->value = $value;
    }

    /**
    * convert value from what unit
    */
    public function from($from){
        // cup to tablespoon
    }

    /**
    * converting value to specific unit
    */
    public function to($to){

    }
}

这基本上是我想要这样做而不是单独调用每个方法。

$var = new UnitConverter();
$var->convert(1)->from('pounds')->to('tbsp');

2 个答案:

答案 0 :(得分:6)

虽然方法链是一件事,但我认为它根本不适合您正在做的事情。

相反,我建议采用更像下面的构图方法。

class Unit {
    protected $type; // the type of unit, to prevent mismatches, eg: volume
    protected $name; // the unit name, eg: mL
    protected $rate; // the conversion rate between the stated unit and the Base unit

    public function __construct(string $name, string $type, float $rate) {
        $this->name = $name;
        $this->type = $type;
        $this->rate = $rate;
    }

    // ToDo: put 'get*()' methods here [I am lazy]
}

class UnitConverter {
    public static function convert(float $amount, Unit $from, Unit $to) {
        if( $from->getType() !== $to->getType() ) {
            throw new Exception('Unit type mismatch, cannot convert!');
        }
        return $amount * $from->getRate() / $to->getRate();
    }
}

$ml  = new Unit( 'mL', 'volume', 1);
$tsp = new Unit('tsp', 'volume', 5.91939);
$gal = new Unit('gal', 'volume', 3785.41);

UnitConverter::convert(1000,  $ml, $gal); // should return 0.2641721769
UnitConverter::convert(1,    $gal, $tsp); // should return 639.4932585959

您可以围绕它构建更多功能,例如:

class Quantity {
    protected $amount;
    protected $unit;

    public function(float $amount, Unit $unit) {
        $this->amount = $amount;
        $this->unit = $unit;
    }

    public function convert(Unit $new_unit) {
        return new $this(
            UnitConverter::convert($this->amount, $this->unit, $new_unit),
            $new_unit
        )
    }
}

$ingredient = new Quantity(2.5, $gal);
$ingredient_metric = $ingredient->convert($ml);

答案 1 :(得分:3)

  

如何将属性从一种方法传递到另一种方法?

方法没有属性,它们有参数(当你调用它们时放在括号中的东西)和返回值。对象具有属性。 Sammitch的答案显示了如何为构造函数中的属性分配参数。

  

$ VAR->转换(1) - >从( '磅') - >到( '汤匙');

以上是一种合法的语法结构(假设方法已正确实现),称为方法链接。

为了实现它,convert($amount)方法必须返回对$var的引用 - 特别是该方法将以类中的return $this;结束。同样地,from($measure)需要返回$ this。

关于to()方法返回的内容是一个语义问题,但惯例是在所有公共方法中使用方法链,或者不使用方法链。因此,要检索结果,您需要添加一个通过引用(而不是按值)获取参数的方法,例如

 protected $amount;
 protected $fromMeasure;
 protected $toMeasure;

 public function convert($amount)
 {
    if (is_numeric($amount)) {
       $this->amount=$amount;
    } else {
       throw new Exception('convert called with non-numeric value');
    }
    return $this;
 }
 public function from($fromMeasure)
 {
    if ($this->is_valid_measure($fromMeasure)) {
       $this->fromMeasure=$fromMeasure;
    } else {
       throw new Exception("Unknown measurement type $fromMeasure");
    } 
    return $this;
 }
 public function getResult(&$result)
 {
    if (!$this->is_valid_conversion()) {
         throw new Exception("Can't convert " 
            . this->fromMeasure . " to "
            . $this->toMeasure);
         return $this;
    }
    if (is_numeric($this->amount) && $this->fromMeasure && $this->toMeasure) { 
        $result=$this->calculate();
    } else {
        throw new Exception('Object calc invoked before primed');
    }
    return $this;
 }
 protected function calculate()
 {
     ... include some calculation....
     return $calculatedResult;
     // note that method does not return $this AND IS NOT PUBLIC
 }

(注意以上内容是故意不完整的,可能会使您的系统通过日志记录暴露给代码注入)

相关问题