duanpoqiu0919 2017-04-04 11:16
浏览 58
已采纳

从函数调用中设置变量是不是很好的编码风格?

Consider these two examples:

// explicitly setting the variable
$file = '/example.php';
if (file_exists($file)) {
  include($file);
}

// setting the variable within a function call
if (file_exists($file = '/example.php')) {
  include($file);
}

I tested both, and they seem to be working identical.
The second one seems much more concise and less prone to errors, despite having less characters. Yet, I've never seen this being used in practice, and guides will usually advertise the first method.

Are there any reasons against setting variables in this manner? If so, are they exclusively of coding style nature, or is there a technical difference? Are there any other differences I haven't addressed?

  • 写回答

1条回答 默认 最新

  • duanjianxu4288 2017-04-04 11:20
    关注

    If anything, the second one is needlessly confusing. In the example above it's not much of a problem (one can infer enough from the names), but consider this one:

    update_user_status($admin = true)
    

    Did the author mean to set $admin variable like that? Or they simply made a typo and it should be an equality check instead ($admin == true)?

    First style is immune to this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大