PHP通过参数传递数组

时间:2016-06-26 17:19:15

标签: php arrays paypal

我试图在PHP中使用PayPal API,但是我在通过函数参数传递数组时遇到了问题。我一直在看this tutorial。如果你在21:00左右看一下,你可以看到他们编写了大部分代码。我对第34和59行遇到了问题:

<?php
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Exception\PayPalConnectionException;

require 'start.php';

if(!isset($_POST['product'], $_POST['price'])) {
    echo "Product or price not set";
    die();
}

$product = $_POST['product'];
$price = $_POST['price'];
$shipping = 2.00;
$total = $price + $shipping;

$payer = new Payer();
$payer->setPaymentMethod('paypal');

$item = new Item();
$item->setName('test')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($price);

$itemList = new ItemList();
$itemList->setItems([$item]);

$details = new Details();
$details->setShipping($shipping)
    ->setSubtotal($price);

$amount = new Amount();
$amount->setCurrency('USD')
    ->setTotal($total)
    ->setDetails($details);

$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setItemList($item)
    ->setDescription('Testing')
    ->setInvoiceNumber(uniqid());

$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true')
    ->setCancelUrl(SITE_URL . '/pay.php?success=false');

$payment = new Payment();
$payment->setIntent('sale')
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions([$transaction]);

try {
    $payment->create($paypal);
} catch (PayPalConnectionException $e) {
    echo $e->getData();

}

echo $approvalUrl = $payment->getApprovalLink();

使用此代码,我使用:

$itemList = new ItemList();
$itemList->setItems([$item]);

$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);

将数组传入方法,如视频中所示。但是这会导致页面无法加载。如果我将我的代码更改为:

$itemList = new ItemList();
$itemList->setItems(array($item));

$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));

然后我收到PayPal错误,我问过here,但似乎没有人知道答案。自从制作视频教程以来,通过方法参数传递数组的语法是否已更改?或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

数组($array = [1,2,3];)的简短语法是added in PHP 5.4。如果您有早期版本的PHP,则需要使用较长的$array = array(1,2,3);语法。

但是 PHP 5.3去年为end-of-lifed in 2014,5.4,而5.5仅在接下来的13天内有安全修复程序。如果您尚未使用5.6或7,则应该强烈考虑升级。