首页 > 解决方案 > 从多个函数中访问数据

问题描述

在我需要在多个函数中访问 3 个计算的地方,有没有比使用函数更好的选择,例如:

public function shipping()
{
    // Calculate shipping into $shipping

    return $shipping;
}

public function tax()
{
    // Calculate tax into $tax

    return $tax;    
}

public function total()
{
    // Calculate total into $total

    return $total;  
}

然后调用:

$this->shipping();

我读过最好避免使用全局变量。

标签: php

解决方案


您可以使用以下代码来减少函数调用

public function getProductCalculations($productId){
    $return = array()
    // Calculate total into $total
    // Calculate tax into $tax
    // Calculate shipping into $shipping
    $return['tax']      = $tax;
    $return['shipping'] = $shipping;
    $return['total']    = $total;
    return $return;  
}

然后你可以得到如下给出的数据

$productCalc = $this->getProductCalculations($productId);

推荐阅读