我是 PHP 面向对象编程的初学者。我想制作一个简单的计算器,我可以输入两个数字并根据我的function
进行计算。我只能在 OOP 中输入两个数字作为参数。但我怎样才能输入两个<form>
中的号码,并在<form>
和variable
之间建立连接并显示输出?作为我的初学者,请原谅我的错误。
谢谢你提前。
我到目前为止尝试的是:
index.php:
<?php
require 'functions.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" >
<title>PHP OOP | Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrapper">
<div class="form_area">
<form action="" method="POST">
<table>
<tr>
<td>First Number :</td>
<td><input type="number" name="numOne" placeholder="Input Your First Number"></td>
</tr>
<tr>
<td>Second Number :</td>
<td><input type="number" name="numTwo" placeholder="Input Your Second Number"></td>
</tr>
<tr>
<td><input type="reset" name="reset" value="Reset"></td>
<td><input type="submit" name="submit" value="Calculate"></td>
</tr>
</table>
</form>
</div>
<div class="output_area">
<?php
if(null !==($_POST['numOne'] && $_POST['numTwo'])){
$resultsOne = new NumberCalculation();
echo "Added Results = ".$resultsOne->add()."<br>";
}
?>
</div>
</div>
</body>
</html>
functions.php:
<?php
class NumberCalculation{
public $numOne;
public $numTwo;
public function __construct($firstNum, $secNum){
$this->numOne = $firstNum;
$this->numTwo = $secNum;
}
public function add(){
return $this->numOne + $this->numTwo;
}
public function subtruct(){
return $this->numOne - $this->numTwo;
}
public function multiple(){
return $this->numOne * $this->numTwo;
}
public function divide(){
return $this->numOne / $this->numTwo;
}
}
global $numOne, $numTwo;
$resultsOne = new NumberCalculation($numOne,$numTwo);
?>
答案 0 :(得分:1)
$_POST
变量输入到NumberCalculation
类构造函数
$resultsOne = new NumberCalculation($_POST['numOne'],$_POST['numTwo']);
echo "Added Results = ".$resultsOne->add()."<br>";
如果您不想将某些内容传递给NumberCalculation
类构造函数。你可以做ff:
$resultsOne = new NumberCalculation();
$resultsOne->numOne = $_POST['numOne'];
$resultsOne->numTwo = $_POST['numTwo'];
echo "Added Results = ".$resultsOne->add()."<br>";
答案 1 :(得分:1)
您没有传递表单发布的值。这样做..
conda install -c https://conda.anaconda.org/menpo opencv3
答案 2 :(得分:0)
添加第三个参数($funcName
)以供全局使用。你只需要传递动作名称,例如add,multiple,divide等。
functions.php:
class NumberCalculation{
public $numOne;
public $numTwo;
private $result;
public function __construct($firstNum, $secNum, $funcName){
$this->numOne = $firstNum;
$this->numTwo = $secNum;
$this->$funcName();
}
public function add(){
$this->result = $this->numOne + $this->numTwo;
}
public function subtruct(){
$this->result = $this->numOne - $this->numTwo;
}
public function multiple(){
$this->result = $this->numOne * $this->numTwo;
}
public function divide(){
$this->result = $this->numOne / $this->numTwo;
}
public function result(){
return $this->result;
}
}
$numOne=3; $numTwo=2; $funcName='multiple';
$resultsOne = new NumberCalculation($numOne,$numTwo,$funcName);
echo $resultsOne->result();