PHP是否支持RAII模式?如何? [英] Does PHP support the RAII pattern? How?

查看:82
本文介绍了PHP是否支持RAII模式?如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP上的大多数资源从不涉及内存管理,因为该语言本身非常擅长为您完成此任务.但是,在PHP中,您通常最终会处理不是内存的外部资源-数据库句柄,会话,数据库事务等.使用某种形式的RAII对象,可以最干净地管理这些外部资源.

Most resources on PHP never touch memory management because the language itself is pretty good at doing this for you. However, in PHP you often end up dealing with external resources which aren't memory -- database handles, sessions, database transactions, etc. These external resources could be managed most cleanly using some form of RAII object.

我最初以为PHP使用了类似于JVM或CLR的垃圾回收方案,其中不存在析构函数的概念. (请记住:每个人都以错误的方式考虑垃圾收集-终结器不是析构函数!)有一种特殊的__destruct方法,但我认为这是一个类似于Java或C#终结器的终结器".因此,您不能在JVM或CLR上使用RAII(C#的using块为您提供了大约95%的访问方式,但这有点不同...).

I initially thought that PHP used a garbage collection scheme similar to the JVM or the CLR, where the concept of a destructor does not exist. (Remember: Everyone thinks about garbage collection the wrong way -- finalizers are not destructors!) There's the special __destruct method, but I thought that was a "finalizer" similar to a Java or C# finalizer. For this reason, you cannot use RAII on the JVM or the CLR (C#'s using blocks get you about 95% of the way there, but that's a bit different...).

但是,

However, Google seems to indicate that PHP supports the RAII pattern, though I cannot find verification of this in the PHP docs. Does the language support this and is putting the cleanup logic in __destruct sufficient for accomplishing RAII tasks?

推荐答案

这几乎与

This is nearly the same question as Is destructor in PHP predictable? and the answer is the same. PHP uses refcounting, and it promises that the destructor will be called immediately as soon as the refcount goes to zero (generally when the object goes out of scope). So if you create an object and take care not to leak it out of scope, RAII is viable.

这篇关于PHP是否支持RAII模式?如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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