koj*_*iro 12 php parameter-passing
我今天发现,除了对象和原语之外,PHP还有资源.该文档指出,默认情况下,php按值传递名称.但我们知道在PHP 5中,对象是由句柄引用的,因此当句柄按值传递时,您可以将句柄视为引用本身,从而避免了问题.
但资源呢?它们是否像对象一样,只是将句柄视为引用本身,还是它们实际上是在传递时被复制的值?
例如:
/**
* Close the ftp connection and throw an exception.
*
* @hack Because php doesn't have a `finally` statement,
* we workaround it to make sure the ftp connection is closed.
* @param resource $conn FTP Buffer
* @param Exception $e
*/
function ftpCloseWithException($conn, $e) {
ftp_close($conn); // <-- Is this the same FTP Buffer resource or a new one?
throw $e;
}
/**
* Copy the README file from ftp.mozilla.org or do something equally arbitrary using ftp.
*/
function getMozReadme() {
try {
$conn = ftp_connect('ftp.mozilla.org');
…
} catch (Exception $e) {
ftpCloseWithException($conn, $e);
}
}
Run Code Online (Sandbox Code Playgroud)
不,他们是不是默认由引用传递,他们在这种情况下,任何其他PHP变量处理.检查此示例:
function test($fd) {
$fd = NULL;
}
$fd = fopen('/tmp/test', 'w+');
test($fd);
var_dump(is_resource($fd)); // bool(true);
Run Code Online (Sandbox Code Playgroud)
......但它是通过它们指向一个资源的性质单一的外部资源.这可以是文件,数据库连接或类似的东西.因此,对资源(或其副本)的任何操作都会对该单个外部资源产生直接影响.
检查此示例:
function close($fd) {
fclose($fd);
}
$fd = fopen('/tmp/test', 'w+');
close($fd);
var_dump(is_resource($fd)); // bool(false);
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,PHP引擎在文件关闭后重置所有范围内对$ fd 的所有引用.这意味着从这种副作用来看,它们可能与其他变量不完全相同.
归档时间: |
|
查看次数: |
2129 次 |
最近记录: |