在php函数之间传递变量值

双加好

我正在尝试$shippingMethodgetMainDetails()函数的值共享给estimateDeliveryDate()同一类中函数以运行条件,但第二个函数似乎没有获取该值:

private function getMainDetails($order)
{
    //This value is correctly being set from my order details in Magento
    $shippingMethod = strtolower($order->getShippingDescription());
}

private function estimateDeliveryDate($orderCreatedDate)
{
    if ($shippingMethod == 'saturday delivery') {
        echo 'Saturday Delivery';
    } else {
        echo 'Standard Delivery';
    } 
}

想知道是否有人可以提供帮助?

谢谢你。

香蕉苹果

您需要将变量添加为属性,如下所示:

class myClass
{
    private $shippingMethod;

    private function getMainDetails($order)
    {
        //This value is correctly being set from my order details in Magento
        $this->shippingMethod = strtolower($order->getShippingDescription());
    }


    private function estimateDeliveryDate($orderCreatedDate)
    {
        if ($this->shippingMethod == 'saturday delivery')
        {
            echo 'Saturday Delivery';
        } else {
            echo 'Standard Delivery';
        }

    }
}

编辑

但是,在这方面更可靠的方法是:

class DeliveryHandler
{
    private $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    private function getDeliveryDateEstimate()
    {
        if ($this->order->getShippingMethod() == 'saturday delivery') {
            return 'Saturday Delivery';
        } else {
            return 'Standard Delivery';
        }

    }
}

class Order
{
    public function getShippingMethod()
    {
        return strtolower($this->getShippingDescription());
    }
}

在那个例子中发生的事情很少。

  1. 我搬进shippingMethod()Order班级,因为这不是DeliveryHandlers 的责任,因此它不必关心该方法中发生的事情。数据属于并来自Order.

  2. getDeliveryDateEstimate()返回一个字符串而不是使用echo. 这使您的代码更具可重用性 - 例如,如果有一天您想将其传递给模板或另一个变量而不是回显它,该怎么办。这样你就可以保持你的选择。

  3. 我使用依赖注入传递Order类进入DeliveryHandler,从而使公共接口Order可用DeliveryHandler

如果您碰巧订阅了 laracast,则可以在此处查看这些课程,它们以易于理解的格式解释了所有这些内容:

https://laracasts.com/series/object-oriented-bootcamp-in-php

https://laracasts.com/series/solid-principles-in-php

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章