我想制作一个基本的计算器。每件事都设置了,文本框和按钮。它需要是OOP,但这给我带来了麻烦。它之前有效,直到我尝试在OOP中完成。
我没有得到错误,但是当我试图让代码计算一个总和时,它会将答案结果为0.这可能是因为该类没有从文本框中获取值,但我不知道如何解决它。
需要计算的类的代码:
class CountUp
{
public static $_sum;
public static $number1;
public static $number2;
public function __construct()
{
self::$_sum;
self::$number1;
self::$number2;
}
public function getnumber1()
{
self::$number1 = ($_POST['number1']);
return self::$number1;
}
public function getnumber2()
{
self::$number2 = ($_POST['number2']);
return self::$number2;
}
public static function getsum()
{
$_sum = self::$number1 + self::$number2;
return $_sum;
}
}
对不起,如果这是一个愚蠢的问题,我对php很不好。
编辑:这是值来自的地方:
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action="test2.php"><br/>
enter a number <br/>
<input type="tekst" name="number1" value=""><br/>
<input type="submit" name="plus" value="+">
<input type="submit" name="retract" value="- "><br/>
<input type="submit" name="divide" value="/ ">
<input type="submit" name="multiply" value="* "><br/>
enter a second number <br/>
<input type="tekst" name="number2" value=""><br/>
</form>
</body>
</html>
EDIT2:我是个白痴,忘了将这部分添加到这个问题中:
<?php
include("plus.class.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['plus']))
{
echo CountUp::getSum();
}
else
{
//still empty for now
}
}
?>
答案 0 :(得分:0)
您正在混合与类定义相关的静态函数。
对象实例函数,它们与您创建的类的每个“新”实例相关。
这里输入表单和类将$ _POST数组值一起添加。
<?php if (!empty($_POST['number1'])) {
// object instance version
class CountUp
{
private $number1 = 0;
private $number2 = 0;
public function setNumber1($number)
{
$this->number1 = $number;
}
public function setNumber2($number)
{
$this->number2 = ($number)
public function getSum()
{
$_sum = $this->number1 + $this->number2;
return $_sum;
}
}
$addTwoNumbers1 = new CountUp();
$addTwoNumbers1->setNumber1($_POST['number1']);
$addTwoNumbers1->setNumber2($_POST['number2']);
?>
<p> The answer of: <?= $_POST['number1']?> + <?= $_POST['number2'] ?> = <?= $addTwoNumbers1->getSum(); ?>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action=""><br/>
enter a number <br/>
<input type="text" name="number1" value=""><br/>
<p>will be added to...</p>
enter a second number <br/>
<input type="text" name="number2" value=""><br/>
<input type="submit" name="plus" value="add the two numbers together...">
</form>
</body>
</html>