Я пытаюсь изучить PHP OOP путем преобразования некоторых упражнений из нескольких классов Java в него. Тонкие различия в стороне, я был относительно успешным до этого преобразования. Идея заключалась в том, что у вас будет банковский счет и баланс для начала. Используя серию типов транзакций, как снятие средств, так и депозит, вы должны вывести остаток после транзакции. Если сумма вывода была больше, чем остаток, она все равно обработает транзакцию и выведет новый баланс с добавленной стоимостью добавленной суммы в размере 30 долларов США. Казалось, достаточно просто.Расчет овердрафта с использованием валидатора
Однако, независимо от того, что я пробовал, он не будет проверять вывод, используя validateWithdrawalAmount, чтобы вернуть «0» или «ЛОЖЬ», если средства недоступны. Я искал онлайн по всему миру и не смог найти Это мой код из моей последней попытки использовать целые числа, а не TRUE/FALSE, которые я пробовал использовать с учетом регистра/-чувствительный. Я подозреваю, что эта проблема связана с некоторой странностью в том, как PHP обрабатывает логическое значение, но я запутался. Любая помощь была бы принята с благодарностью!
Пожалуйста, имейте в виду, что они направлены на обучение, а не на красоту. Однако, если вы видите что-то, что может улучшить мой код, вне решения, не стесняйтесь, дайте мне знать. всегда ищу конструктивную критику. Я добавил комментарии, чтобы помочь с пониманием г.
class_bank_account.php
<?php
class BankAccount
{
// constant(s)
const OVERDRAFT_CHARGE = 30;
// variable(s)
private $accountNumber;
private $balance;
/**
* Construct the object with set parameters.
*
* @param String $sAccountNumber Account number to use.
* @param Double $dBalance Starting balance.
**/
public function __construct($sAccountNumber, $dBalance)
{
$this->accountNumber = $sAccountNumber;
$this->balance = $dBalance;
}
/**
* Process a withdrawal by, first, checking to see if there are
* sufficient funds and then subtract the amount of the transaction
* from the balance. If the balance is less than the transaction
* amount then add the overdraft fee.
*
* @param Double $dWithdrawal Withdrawal amount.
**/
public function processWithdrawal($dWithdrawal)
{
// check if the withdrawal amount is in good standing with internal function
$goodStanding = $this->validateWithdrawalAmount($dWithdrawal);
// process withdrawal
if($goodStanding == 0)
{
$this->balance += $dWithdrawal - self::OVERDRAFT_CHARGE;
}
elseif($goodStanding == 1)
{
$this->balance += $dWithdrawal;
}
else
{
echo "error"; // this was added as a way to confirm flow
}
}
/**
* Validates the withdrawal amount to confirm if there are
* sufficient funds or not.
*
* @param Double $dWithdrawal Withdrawal Amount
* @return Boolean True or False
**/
public function validateWithdrawalAmount($dWithdrawal)
{
$sufficientFunds = 1;
if($dWithdrawal > $this->balance)
{
$sufficientFunds = 0;
}
return $sufficientFunds; // return either 1 or 0 for True or False
}
/**
* Processes deposits into the account.
*
* @param Double $dDeposit Deposit amount.
**/
public function processDeposit($dDeposit)
{
$this->balance += $dDeposit;
}
/**
* Get the account number.
*
* @return String Account number.
**/
public function get_AccountNumber()
{
return $this->accountNumber;
}
/**
* Set the account number.
*
* @param String $sAccountNumber Account number to use.
**/
public function set_AccountNumber($sAccountNumber)
{
$this->accountNumber = $sAccountNumber;
}
/**
* Get the account balance.
*
* @return Double Account balance.
**/
public function get_Balance()
{
return $this->balance;
}
}
?>
bankdriver.php
<!DOCTYPE html>
<html>
<head>
<title>Bank Driver</title>
</head>
<body>
<?php
// our class
include "class_bank_account.php";
// array of transactions
$trans = array(
-20.00,
120.00,
-35.00,
-251.00,
-2000.00,
3000.00,
-4.00,
-60.00,
-555.00
);
// length of array for counting foreach loop
$array_length = count($trans);
// create our bank account object
$account = new BankAccount("BJS15923", 2000);
?>
<h1><?php echo $account->get_AccountNumber(); ?></h1>
<table border="1px" width="50%">
<tr><th>AMOUNT</th><th>BALANCE</th></tr>
<tr><td> </td><td><?php echo $account->get_Balance(); ?></td></tr>
<?php
// cycle through the array
foreach($trans as $amount)
{
// output the amount of the transaction
echo '<tr><td>'.$amount.'</td><td>';
if($amount < 0)
{
// processess withdrawal if transaction was negative
$account->processWithdrawal($amount);
}
elseif($amount > 0)
{
// process deposit if transaction was positive
$account->processDeposit($amount);
}
// output our new balance
echo $account->get_Balance().'</td></tr>';
}
?>
</table>
</body>
</html>
Ваш 'self ::' должен быть '$ this->' –
К сожалению, это не сработало. Проблема в том, что в функции «validateWithdrawalAmount» она никогда не входит в оператор if, так как никогда не думает, что баланс меньше суммы вывода, переданной в нее. Я могу проверить это, добавив эхо переменной $ good в функции processWithdrawal. – ubelong2matt
Думаю, я справился с этим - вывод отрицательный, поэтому отрицательный результат не будет больше, чем баланс, вам нужно сравнить вывод как абсолютное значение (абс), а не отрицательное. oop - это файл, его логический вопрос –