duanping1632 2019-08-08 10:36
浏览 27

PHP:return和echo之间的区别[重复]

I'd like to know the difference in PHP when using either return or echo as reading on Laravel forums tends to contradict points made in other questions such as this:

Difference between echo and return in php?

If I have something like this:

/**
 * Generate an appropriate response given the details that were entered by the client
 *
 * @param array $intent
 * @return void
 */
public function generatePaymentResponse(array $intent)
{
    # Note that if your API version is before 2019-02-11, 'requires_action'
    # appears as 'requires_source_action'.
    if (
        $intent['status'] == 'requires_source_action' &&
        $intent['next_action']['type'] == 'use_stripe_sdk'
    ) {
        # Tell the client to handle the action

        echo json_encode([
            'requires_action' => true,
            'payment_intent_client_secret' => $intent['client_secret']
        ]);
    } else if ($intent['status'] == 'succeeded') {
        # The payment didn’t need any additional actions and completed!
        # Handle post-payment fulfillment
        echo json_encode([
            "success" => true
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Invalid PaymentIntent status']);
    }
}

Why is this not the equivalent?

/**
 * Generate an appropriate response given the details that were entered by the client
 *
 * @param array $intent
 * @return void
 */
public function generatePaymentResponse(array $intent)
{
    # Note that if your API version is before 2019-02-11, 'requires_action'
    # appears as 'requires_source_action'.
    if (
        $intent['status'] == 'requires_source_action' &&
        $intent['next_action']['type'] == 'use_stripe_sdk'
    ) {
        # Tell the client to handle the action
        return response()->json([
            'requires_action' => true,
            'payment_intent_client_secret' => $intent['client_secret']
        ], 200);
    } else if ($intent['status'] == 'succeeded') {
        # The payment didn’t need any additional actions and completed!
        # Handle post-payment fulfillment
        return response()->json([
            'success' => true
        ], 200);
    } else {
        return response()->json([
            'error' => 'Invalid PaymentIntent status'
        ], 500);
    }
}

The script in the frontend is as follows:

<script src="https://js.stripe.com/v3/"></script>

<script>
    // Create a new Stripe client
    var stripe = Stripe('{{ config('services.stripe.key') }}');

    // Create a new instance of Elements
    var elements = stripe.elements();

    // Create a card element and bind it to a <div>
    var cardElement = elements.create('card');
    cardElement.mount('#card-element');

    // Store elements needed as variables
    var cardButton = document.getElementById('card-button');

    // Bind a click event to the card button
    cardButton.addEventListener('click', function(ev) {
      stripe.createPaymentMethod('card', cardElement)
      .then(function(result) {
        if (result.error) {
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
        } else {
            // Otherwise send paymentMethod.id to your server (see Step 2)
            fetch('/confirm_payment', {
                method: 'POST',
                headers: { 
                  'Content-Type': 'application/json', 
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({ payment_method_id: result.paymentMethod.id })
            }).then(function(result) {
                // Handle server response (see Step 3)
                result.json().then(function(json) {
                  handleServerResponse(json);
                })
            });
          }
      });
  });

function handleServerResponse(response) {
  if (response.error) {
    var errorElement = document.getElementById('card-errors');
    errorElement.textContent = result.error.message;
  } else if (response.requires_action) {
    // Use Stripe.js to handle required card action
    stripe.handleCardAction(
      response.payment_intent_client_secret
    ).then(function(result) {
      if (result.error) {
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
        // The card action has been handled
        // The PaymentIntent can be confirmed again on the server
        fetch('/confirm_payment', {
          method: 'POST',
          headers: { 
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          body: JSON.stringify({ payment_intent_id: result.paymentIntent.id })
        }).then(function(confirmResult) {
          console.log(confirmResult);
          return confirmResult.json();
        }).then(handleServerResponse);
      }
    });
  } else {
        var errorElement = document.getElementById('card-errors');
        console.log(response);
  }
}

</script>

Why is it that when I use return nothing is returned by the console but with echo it is?

When I have previously used the axios library the server functions have always explicitly returned JSON and not echoed it.

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求daily translation(DT)偏差订正方法的代码
    • ¥15 js调用html页面需要隐藏某个按钮
    • ¥15 ads仿真结果在圆图上是怎么读数的
    • ¥20 Cotex M3的调试和程序执行方式是什么样的?
    • ¥20 java项目连接sqlserver时报ssl相关错误
    • ¥15 一道python难题3
    • ¥15 牛顿斯科特系数表表示
    • ¥15 arduino 步进电机
    • ¥20 程序进入HardFault_Handler
    • ¥15 关于#python#的问题:自动化测试