首页 > php > Laravel 4:Input :: has()+ Input :: get()vs.($ var = Input :: get())!= null

Laravel 4:Input :: has()+ Input :: get()vs.($ var = Input :: get())!= null (Laravel 4: Input::has() + Input::get() vs. ($var = Input::get()) != null)

问题

检查是否存在输入值并将其分配给变量时,我看到两种方法来实现:

if(Input::has('id')) {
    $id = Input::get('id');
    // do some stuff
}

或者更短if(Input::has('id') && $id = Input::get('id')) {...},和

$id = Input::get('id');
if($id != null) {
    // do some stuff
}

分别if(($id = Input::get('id')) != null) {...}

显然第一种方法更多的是Laravel方式,可能更直观(至少要阅读),但一方面第二种方法似乎更快,因为它涉及更少的方法调用,而另一方面可能更慢的不必要的变量在案件中的转让id == null

那么是否有一种方式可以选择或者可能还有其他一些我尚未意识到的问题?

解决方法

我总是喜欢我的代码的可读性,而不是几毫秒的代码执行速度。

if(Input::has('id')) {
    $id = Input::get('id');
    // do some stuff
}

可能比较慢但是这个稍微有点无关紧要。

问题

When checking for presence of an input value and assigning it to a variable I see two ways to achieve this:

if(Input::has('id')) {
    $id = Input::get('id');
    // do some stuff
}

or maybe shorter if(Input::has('id') && $id = Input::get('id')) {...}, and

$id = Input::get('id');
if($id != null) {
    // do some stuff
}

respectively if(($id = Input::get('id')) != null) {...}.

Obviously the first method is more the Laravel way and might be more intuitive (at least to read) but on the one hand the second method seems to be faster as it involves less method calls while on the other hand being potentially slower for the needless variable assignment in the case of id == null.

So is there one way to prefer or maybe some other concerns I am not (yet) aware of?

解决方法

I would prefer always the readability of my code over milliseconds of faster code execution.

if(Input::has('id')) {
    $id = Input::get('id');
    // do some stuff
}

is possibly slower but this is so slightly that it doesn't matter.

相似信息