2017-02-11 50 views
-2

我已經做了一個PHP頁面,將形成一個窗體併發布信息給自己。然後我用它創建一個對象,我通過一個方法來運行,我想返回/回顯一個字符串,這是我的代碼。試圖回聲的方法PHP的值

<?php 
include_once 'checkLogin.php'; 
$action='';//this will store what the user wants to do 
if(isset($_GET['savings'])){$action='save';} 
if(isset($_GET['depreciation'])){$action='deprec';} 
$time=$_POST['time'];//get the values from the form below 
$interest=$_POST['interest']; 
$InitialSum=$_POST['InitialSum']; 
    //depreciation and savings can be done on the same page 
class Information{ 
    function __construct($time,$interest,$InitialSum){ 
    $this->time=$time; 
    $this->interest=$interest; 
    $this->InitialSum=$InitialSum; 
    } 
    function CalcSave(){ 
    $totalAmt=$InitialSum*($interest*100);//the total amount, this will count as one year 
    for ($x=0;$x<$time;$x++){//therefore this should only do 1 less than the total 
     $totalAmt=($interest*100)*$totalAmmt;//after another year 
    } 
    return'After '.$time.' years your savings will be worth '.$totalAmt.'.'; 
    } 
    function CalcDeprec(){ 
    $totalAmt=$InitialSum*$interest; 
    for ($x=0;$x<$time;$x++){//therefore this should only do 1 less than the total 
     $totalAmt=$interest*$totalAmmt;//after another year 
    } 
    return 'After'.$time.'years your asset will be worth '.$totalAmt.'.'; 
    } 
} 
?> 
<!DOCTYPE HTML> 
<html> 
<body> 
    <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > 
Initial Amount: <input type="number" name="InitialSum"><br> 
Interest: <input type="number" name="interest"><br> 
How long: <input type='number' name='time'><br> 
<input type="submit"> 
</form> 
<p> 
    <?php 
    $user=new Information($time,$interest,$InitialSum);//this creates the user object 
    if ($action=='save'){ 
    $user->CalcSave();//this will run the method since user is the object 
    echo $result; 
    } 
    if ($action=='deprec'){ 
    $user->CalcDeprec(); 
    echo $result; 
    } 
    ?> 
</p> 
</body> 
</html> 

,如果去到不同的網頁,但最好我想這回顯到頁面上,我不介意。我沒有從它得到任何錯誤,我不是非常有經驗的OOP在PHP中。 編輯我試過$result = $user->CalcSave(); echo $result;

echo $user->CalcSave(); 

,但它在頁面的末尾重新加載相同的頁面而不

?action=depreciation 

,並沒有什麼迴應。

+0

'回聲$用戶> CalcSave();'和'回聲$用戶> CalcDeprec();' – RiggsFolly

回答

0

試試這個:

$result = $user->CalcSave(); 
echo $result; 

和:

$result = $user->CalcDeprec(); 
echo $result; 
+3

爲什麼要OP 「使用此代碼」?一個**好的答案**總是會解釋做了什麼以及爲什麼這樣做, 不僅適用於OP,而且適用於SO的未來訪問者,可能會發現此問題並正在閱讀您的答案。 – RiggsFolly

+0

或者簡單地'echo $ user-> CalcSave();'並且忘記創建一個不必要的標量變量 – RiggsFolly

+0

這不起作用。 – Awtthem