【问题标题】:Proper way of assigning variables分配变量的正确方法
【发布时间】:2014-09-10 00:45:18
【问题描述】:

有人可以介绍一种更有效或更正确的在 php 中分配变量的方法吗?

这是我的代码的 sn-p:

类 PurchaseController 扩展 BaseController {

/**
*Gets input form form
*
*@var input
*/

protected $input;

public function postPurchaseCheck()
{   
    $input = Input::all();
    $this->input = $input;

如果表单提交按钮的值为“购买”,则使用 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 中执行此操作而无需为每个方法重新分配变量 } }

【问题讨论】:

  • 没有明显的理由让您以这种方式为每个输入创建局部变量。为什么不直接使用来自$this->input 的值?

标签: php variables variable-assignment


【解决方案1】:

你可以像下面的代码那样做,会节省几行......

<?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-&gt;input['memory'] 等,而不是将它们重新分配给局部变量。

也是你做的,基本上就是在浪费内存(同上):

$input = Input::all();
$this->input = $input;

只需:$this-&gt;input = Input::all();

【讨论】:

    【解决方案2】:

    您可以使用 extract 方法,但我会谨慎对待这个带有输入的函数。几乎你会让自己回到注册全局变量。

    http://php.net/manual/en/function.extract.php

    http://php.net/manual/en/security.globals.php

    为什么不能直接使用输入中的值?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多