简体   繁体   中英

Object Oriented PHP how does function __destruct come into play?

In PHP, when defining classes; there's often a __construct (constructor) and a __destruct (destructor) implemented into an object when it is created and 'destroyed'.

In PHP, an object is 'destroyed' when it stops being used

Now, how is that helpful? How is it used exactly and in which cases will it become handy in a programming language such as PHP?

"When an object is no longer needed it has to be deleted. Objects created within functions as local variables. (...) Whenever an object is deleted its destructor member function is called. Its understandable why constructors are so important, objects must be properly initialised before they can be used, but is it really necessary to have a special member function that gets called when the object is about to disappear?

In many cases the answer is no, we could leave the compiler to invent a default no-op one. However suppose your object contained a list of detector hits from which it was built. Without going into detail, its likely that this would be some kind of dynamic object owned by the object and accessed via a pointer. Now when it comes time to delete the object, we want this list to be deleted, but probably not the hits that it points to! The compiler cannot possibly know, when it comes across a pointer in an object whether it points to something owned by the object and to be deleted as well, or simply something related to, but independent of, the object.

So the rule is If an object, during its lifetime, creates other dynamic objects, it must have a destructor that deletes them afterwards. Failure to tidy up like this can leave to orphan objects that just clog up the memory, something that is called a memory leak. Even when a default is acceptable, its a good idea to define a destructor..."

See more: OO Concept: Constructors & Destructors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM