如何从表单中获取值$ val1,$ val2?
可能需要使用类似于此的设计:
$obj->Calculator($_POST['val1'], $_POST['val1']);
但是..在哪里粘贴?
<?php
class Calculator {
private $_val1 , $_val2;
public function __construct($val1, $val2){
$this->_val1 = $val1;
$this->_val2 = $val2;
}
public function add(){
return $this->_val1 + $this->_val2;
}
public function subtract(){
return $this->_val1 - $this->_val2;
}
public function multiply (){
return $this->_val1 * $this->_val2;
}
public function divide () {
return $this->_val1 / $this->_val2;
}
}
$calc = new Calculator(3,4);
echo "<p>3 + 4 = ".$calc->add(). "</p>";
?>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action='' method='POST'>
Enter Number:
<input type='text' name='val1' value="<?=$val1;?>">
<input type='text' name='val2' value="<?=$val2;?>">
<input type='submit' name='submit' value='Calculate'>
</form>
</body>
</html>
答案 0 :(得分:1)
您可以使用以下内容:
$val1 = (int) $_POST['val1'];
$val2 = (int) $_POST['val2'];
$calc = new Calculator($val1, $val2);
echo '<p>'.$val1.' + '.$val2.' = '.$calc->add().'</p>';
编辑:您还可以在构造函数中键入强制转换变量:
class Calculator {
private $_val1 , $_val2;
public function __construct($val1, $val2){
$this->_val1 = (int) $val1;
$this->_val2 = (int) $val2;
}
...
}
$val1 = $_POST['val1'];
$val2 = $_POST['val2'];
$calc = new Calculator($val1, $val2);
echo '<p>'.$val1.' + '.$val2.' = '.$calc->add().'</p>';
答案 1 :(得分:0)