donglian1982 2017-10-04 08:14
浏览 15

是否有必要将值放入变量?

I have been asked about this simple question by a student and I was greatly troubled because I cannot provide a sufficient answer to this. What I understood is that, a variable is just a container that holds a value. Aside from that, I cannot provide a logical explanation to them.

example:

I want to check if an age is minor or not. By using a variable, I will make it this way:

<?php 
$age = 30;
if( $age > 18)
   echo 'You are no longer a minor';
?>

But, without using a variable, I can make it this way:

<?php  
if( 30 > 18)
   echo 'You are no longer a minor';
?>

If the two scripts produce the same output, then why should we put it in a variable, for in fact, we can lessen the code of we'll not use a variable. And also, Is it necessary to put a value into a variable?

Does it affect the memory of a computer?

  • 写回答

4条回答 默认 最新

  • doushan15559 2017-10-04 08:28
    关注

    The answer here is that age in any valid usage will come from some form of input (user input, database select, webservice call etc) which would be stored in a variable in order to proceed with the rest of the logic. Your example here tries to falsify the input by setting the variable to a predefined value, which is all cool and dandy for examples, but in normal situations you would read that value from somewhere, hence the variable

    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备