所以這裏是我想要做的,我有一個類,在SomeClass
之內,有一個函數由2個變量組成,每個變量都有一個數值。我想返回兩個變量的數組,這兩個變量在SomeClass
以外的發佈數據中有一個從發佈到自身的表單。從對象傳遞變量數組
<?php
class SomeClass{
private $someVar1;
private $someVar2;
public function setVars($var1,$var2) {
$this->someVar1 = $var1;
$this->someVar2 = $var2;
}
function __construct() {
}
function setFraction() {
$sum['num'] = 140*pow($this->someVar1,0.75);
$sum['den'] = $sum['num']/$this->someVar2;
return $sum;
}
}
if(isset($_POST['num'])){$num = preg_replace('/\D/', '', $_POST['num']);}
elseif(isset($_POST['den'])){$den = preg_replace('/\D/', '', $_POST['den']);}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Numerator:<input type="text" value="<?php if(isset($num)){echo $num;}?>" name="num" /><br />
Denominator:<input type="text" value="<?php if(isset($den)){echo $den;}?>" name="den" /><br />
<input type="submit" value="Go" name="Go">
</form>
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$sum=$obj->setFraction();?>
<pre>
<?php print_r($obj->setFraction());?>
</pre>
<ul>
<?php foreach($sum as $val):?>
<li><?php echo $val['num']?></li>
<li><?php echo $val['den']?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
當我運行該腳本,正在發送,並與setFraction()
回來了,但是當我試圖通過在foreach循環數組迭代,我沒有得到任何回報數據$num
和$den
後的數據。我確信它的一些簡單的東西,我用foreach循環嘗試過,沒有相同的結果,任何幫助都很好,thx。
編輯:
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$array = $obj->setFraction();?>
<ul>
<li><?php echo $array['num']?></li>
<li><?php echo $array['den']?></li>
</ul>
<?php endif;?>
你沒有指定'$金額= $ obj-> setFraction();''到$ sum' – XMen