有人可以介绍一个更有效或适当的方式分配变量在php?
下面是我的代码片段:
类PurchaseController扩展BaseController{
/**
*Gets input form form
*
*@var input
*/
protected $input;
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
如果表单提交按钮的值为"buy",则使用postPurhcase方法
if (Input::get('buy')) {
$this->postPurchase();
}
elseif (Input::get('cart')) {
$this->postAddCart();
}
}
public function postAddCart()
{
//Add these items to cart
echo "Add these items to cart";
$memory = $this->input['memory'];
$color = $this->input['color'];
$size = $this->input['size'];
$price = $this->input['price'];
$battery = $this->input['battery'];
$accessories = $this->input['accessories'];
......... 等
}
public function postPurchase()
{
//Get prices, item id, etc and send user to checkout page
$memory = $this->input['memory'];
$color = $this->input['color'];
$size = $this->input['size'];
$price = $this->input['price'];
$battery = $this->input['battery'];
$accessories = $this->input['accessories'];
.........等等。我想知道是否有一种更快的方法在php中做到这一点,而不必为每个方法重新分配变量}}
您可以像下面的代码那样做,将节省几行…
<?php
//loop an expected array, check and set from input
foreach(array('memory','color','size','price','...') as $key){
$$key = isset($this->input[$key]) ? $this->input[$key] : null;
}
?>
$$key
= http://php.net/manual/en/language.variables.variable.php
但是你也可以使用$this->input['memory']
ect,而不是将它们重新分配给局部变量。
也是你的做法,这基本上只是浪费内存(如上所述):
$input = Input::all();
$this->input = $input;
Just do: $this->input = Input::all();
您可以使用提取方法,但我会谨慎使用此函数与输入。基本上你会把自己放回到注册全局。
http://php.net/manual/en/function.extract.php http://php.net/manual/en/security.globals.php为什么不能直接使用输入的值?