简体   繁体   English

如何在一个 function 中初始化一个全局变量并在另一个 function 中访问

[英]How to initialize a global variable inside one function and access in another function inside Laravel controller

I know a global variable should be initialized by contractor.我知道一个全局变量应该由承包商初始化。 what if need to init a global variable inside one function and access it in another function.如果需要在一个 function 中初始化一个全局变量并在另一个 function 中访问它怎么办?

this is my first function这是我的第一个 function

    public $customerId;

    public function store(CheckoutRequest $request)
    {
        try {
            $customer = Stripe::customers()->create([
                                'source' => $request->stripeToken,
                                'email' => $request->email,
                                'description' => $request->name
                            ]);

            **$this->customerId** = $customer->id;
            $this->chargeCustomer($request, $customer->id);
            return redirect()->route('shipper.payment')->with('success_message', 'Thank you! your payment was successfull.');
        } catch (Exception $e) {
            return back()->withErrors('Error! ' . $e->getMessage());
        }
    }

this is my second function这是我的第二个 function

    public function paymentDetails()
    {
        return $this->customerId;
    }

I'm creating customer in Stripe and assign created customer id to $customerId global variable, I need $customerId insid paymentDetails function which gets calling by another route, but paymentDetails return null.我在 Stripe 中创建客户并将创建的客户 ID 分配给 $customerId 全局变量,我需要 $customerId 在 paymentDetails function 中,它通过另一条路线调用,但 paymentDetails 返回 null。 could anyone help please, how to get customer id in other functions?谁能帮忙,如何在其他功能中获取客户ID?

If you, as you describe, are calling paymentDetails() later via another route, then the public variable will not be set anymore.如您所述,如果您稍后通过另一条路线调用paymentDetails() ,则将不再设置公共变量。 The controller is resolved per request, so it does not store anything for the next request. controller 是按请求解析的,因此它不会为下一个请求存储任何内容。

Your best bet is probably to store some the customer on your own end and use that to retrieve the customerId on the next request, or maybe use https://laravel.com/docs/7.x/session您最好的选择可能是在您自己的一端存储一些客户并使用它在下一个请求中检索 customerId,或者使用https://laravel.com/docs/7.x/session

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM