使用我的第一个OOP应用程序,我在访问类中公共函数返回的数组值时遇到了一些问题。这是函数 -
//Process new transaction
public function addTransaction($amount, $payee, $category, $date, $notes) {
global $db;
//Check to see if payee exists in Payee table
$checkPayee = $db->prepare("SELECT * FROM payees WHERE name = ?");
$checkPayee->execute(array($payee));
$checkPayeeNum = $checkPayee->fetchColumn();
$payeeDetails = $checkPayee->fetch();
if ($checkPayeeNum < 1) {
$insertPayee = $db->prepare("INSERT INTO payees (name, cat) VALUES(?, ?)");
$insertPayee->execute(array($payee, $cat));
} else {
if ($payeeDetails['cat'] == "") {
$updatePayee = $db->prepare("UPDATE payees SET cat=? WHERE name=?");
$updatePayee->execute(array($cat, $payee));
}
}
//Process the transaction
$proc = $db->prepare("INSERT INTO transactions (amount, payee, cat, date, notes) VALUES (?, ?, ?, ?, ?)");
$proc->execute(array($amount, $payee, $cat, $date, $notes));
//Prepare array for JSON output
$todaysTrans = $this->fetchDailyTotal();
$weeklyTotal = $this->fetchWeeklyTotal();
$accountBalance = $this->balanceAccount();
$jsonOutput = array("dailyTotal" => $todaysTrans, "weeklyTotal" => $weeklyTotal, "accountBalance" => $accountBalance);
return $jsonOutput;
}
实例化对象不是问题,试图弄清楚如何访问$jsonOutput
数组。如何实现这一目标?
谢谢!
答案 0 :(得分:2)
// In some other PHP file...
include 'YourClass.php';
$yourObject = new YourClass();
$returnedArray = $yourObject->addTransaction(...);
// Access the returned array values
echo 'Daily Total: ', $returnedArray['dailyTotal'], "\n";
echo 'Weekly Total: ', $returnedArray['weeklyTotal'], "\n";
echo 'Account Balance: ', $returnedArray['accountBalance'], "\n";
另外,对于它的价值而言,返回名为$jsonOutput
的PHP数组非常困惑,因为它不是JSON编码的,这是大多数开发人员所期望的。如果您希望对其进行JSON编码,请使用json_encode()
(有关详细信息,请参阅here)。