PHP中赋值的评估 [英] evaluation of assignment in php

查看:56
本文介绍了PHP中赋值的评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php有一个基本"问题.在 fgets 的示例代码中,此代码段作为阅读全文的示例文件内容:

I have a kind of 'basics' question about php. In the example code for fgets, it has this snippet as an example of reading through a file's contents:

while (($buffer = fgets($handle, 4096)) !== false) {
    echo $buffer;
}

语句($buffer = fgets($handle, 4096))可以有一个值是怎么回事?是$buffer的一种赋值+评估吗?我的意思是,它如何获得其价值?有这个名字吗?我注意到它使用严格的比较,因此所有分配的结果都为布尔值true或false吗?

How is it that the statement ($buffer = fgets($handle, 4096)) can have a value? Is it a kind of assignment+evaluation of $buffer? I mean, how does it get its value? Is there a name for this? I notice its using strict comparison, so do all assignments evaluate to a boolean true or false?

如果我想编写一个可以用这种方式处理的函数,除了在某些情况下返回false之外,我是否还需要做其他特别的事情?

If I wanted to write a function that could be treated this way, do I have to do anything special, other than return false on certain conditions?

推荐答案

在PHP中,赋值是一个表达式,即它返回一个值. $buffer = fgets($handle, 4096)首先将值分配给$buffer,然后返回分配的值.

In PHP an assignment is an expression, i.e. it returns a value. $buffer = fgets($handle, 4096) will first assign the value to $buffer and then return the assigned value.

因此,基本上,您可以编写:

So, basically, you could write:

$buffer = fgets($handle, 4096);
while ($buffer !== false) {
    echo $buffer;

    $buffer = fgets($handle, 4096);
}

您将在此处将作业分配在单独的行上.因为在这种情况下,您需要重复分配,所以循环条件下的分配是首选.

Here you would have the assignment on a separate line. Because in that case you need to duplicate the assignment, the assignment in the loop condition is preferred.

PS:while循环中最常见的分配示例可能是从mysql获取行:

PS: The most common example for an assignment in a while loop is probably fetching rows from mysql:

while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'] . ' ' . $row['lastname'];
}

这篇关于PHP中赋值的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆