Passing an array of variables FROM an object
这是我想要做的,我有一个类,在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?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();?> [cc lang="php"] <?php print_r($obj->setFraction());?> |
- <?php foreach($sum as$val):?>
- <?php echo$val['num']?>
- <?php echo$val['den']?>
<?php endforeach;?>
<?php endif;?>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <P>当我运行脚本时,<wyn>$num</wyn>和<wyn>$den</wyn>的post数据被发送并随<wyn>setFraction()</wyn>返回,但是当我尝试在foreach循环中迭代数组时,我没有得到任何返回数据。我相信这很简单,我用foreach循环尝试过,如果没有同样的结果,任何帮助都是很好的,thx。</P><P>编辑:</P>[cc lang="php"]<?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;?> |
您没有将
au您没有将EDOCX1的返回值(0)分配给变量。你需要做的是:
1 | $sum=$obj->setFraction(); |
号
一切都应该正常。
只是因为返回一个名为
我刚刚注意到,正如你在接受时所说的,你不需要
将返回的数据存储到某个变量中,然后迭代。
/ /
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php if(isset($num,$den)): $obj = new SomeClass(); $obj->setVars($num,$den); $array = $obj->setFraction();?> <ul> <?php foreach($array as $val):?> <li> <?php echo $val['num']?> </li> <li> <?php echo $val['den']?> </li> <?php endforeach;?> </ul> <?php endif;?> |
您应该使用$obj->sum而不是$sum。