Is the __destruct method necessary for PHP? - php

The manual said that
The destructor method will be called as soon as all references to a
particular object are removed or when the object is explicitly
destroyed or in any order in shutdown sequence.
Doesn't the PHP GC enough? Could someone give an example that __destruct method is necessary?

A destructor has nothing directly to do with releasing memory - instead it is a "hook" to allow custom code to be run when the object is eligible for reclamation. That is, it's the opposite of the constructor - the constructor does not allocate the memory (as that is done by the GC prior to the constructor being invoked) and thus the destructor does not release the memory (as that will be done by the GC afterwards).
While the GC can manage native resources (e.g. other objects and object graphs) just fine, external resources such as file handles must still be "manually disposed". For instance, imagine a MyFile class, where the destructor would ensure the file, if open, would be closed - while it is arguably "better" to make it a requirement to invoke a Close/Dispose operation upon the object, the destructor can be used as a fall-back mechanism in this case.
I would argue against the general use of destructors in languages with a GC. There are a number of subtle issues they can introduce such as apparent non-determinism and the ability to accidentally keep objects alive - even in languages like PHP that uses reference-counting. (The Java/JVM and .NET models use finalizers which are even more finicky.)
Happy coding.

If you're using exceptions, you should try to follow RAII even with PHP. And you must use destructors for RAII. It was invented for C++ but the same logic works with PHP, too. Be warned that in some cases (e.g. fatal error or when exit() is called) PHP may end up calling the destructors in incorrect order which I consider a bug in PHP engine. For normal code and exceptions, the PHP engine seems to work as if it was C++ program.
See also: Can I trust PHP __destruct() method to be called?

The __destruct magic method is necessary for PHP in the sense that if you want the power to explicitly, automatically, and consistently lower the reference count for injected objects (say, a database wrapper object, etc...), that happen to be shared with other objects, then the __destruct magic method is a reliable and predictable place to do this. Sure, it is more of a convention than an absolute requirement, but why reinvent the wheel (C++, Java, etc ...)? PHP is not just for webpages, so we should keep that in mind.

Related

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

Are DAO objects better than static DAO classes in PHP?

I understand the reasons for not using statics in Java.
However, I'm currently developing OO code in PHP. I use DAOs with the goal of keeping my queries in one place so I can easily find them. I also instantiate some DAOs so I can incorporate pagination in some (relevant) queries. In many cases, it's not necessary and so I tend to just create static methods (even though technically I don't think I can call that a DAO) in the form:
$info = schemeDAO::someFunction($variable);
I may need only that single method during a page refresh (i.e. a specific value in a header file).
I may need to instantiate the same DAO a hundred times as objects are created and destroyed.
$dao = new myDao();
$info = $dao->someFunction($variable);
Either way, it seems to me, in PHP at least, wouldn't it be more performance efficient to simply load a static and keep it in memory?
While the static access is acceptable (to an extent), with the dynamic approach you can pass the object transitively to the 3rd side object via dependency, (otherwise also the transitive call the transition of dependency would have to be initiated from the original class), which needs not to be pushed some data, but rather the dependency decides and pulls the data/method it needs be it multiple times in a single method. Otherwise way it can only return, while instance can be called, not-separated wrapper method logic from data. Instance inline code seems to be shorter, and when you remove an instance, all their calls complain at that moment, whereas static class continues to preserve unnoticed in the code as they don't need the instantiation prerequisite.
Static classes preserve their state in between various objects, and methods contexts and thus are not automatically "reset" as it is with the 'new construct'. Instances encourage more transparent pure functions approach - passing parameters. When you pass an object, you don't separate the service logic from it's data structure, when you pass only the array data structure, the execution logic is lost in transit or separated into another place and must be eventually called intransparently statically when not-passed - pure functions concept.
I would use comparison with Einsteins vs Newton's equations. In some cases, they look totally the same. But to be pretty content I would use more versatile instances or service locator singletons, vs static classes. On the other side, the less "versatile" static classes might be initially easier to implement, especially if you don't plan on rocket with them as far as to the space orbit as you might get with instances. Similarly as with private attributes you signal they are not passed anywhere, pure functions, though it might less often signalize also the bad, being called from anywhere.

Alternatives to persisting objects than using __destruct() in PHP

I usually use a classes destructor method __destruct() to persist objects to session or what have you. It is just very convinient, but I'm curious to if there are any other methods that are equally appealing. Do you know of such?
The curiousity arose as I was to merge/utilize two frameworks that both made use of __destruct() for persistance resulting in a race-problem.
You should handle the persistence manually and explicitly. Not only is it more intuitive for anyone who has to read your code, but it's not a good idea to depend on PHP's garbage collector to do important jobs for you, since it can be unpredictable. Your objects may not be saved in the right order, either, if that matters.
It also prevents many debugging nightmares.

PHP method chaining benefits?

Still on the PHP-OOP training wheels, this question may belong on failblog.org. =)
What are the benefits of method chaining in PHP?
I'm not sure if this is important, but I'll be calling my method statically. e.g.
$foo = Bar::get('sysop')->set('admin')->render();
From what I've read, any method which returns $this is allowed to be chained. I just learned this is new in PHP5. Seems to me there may be speed benefits if I don't have to instantiate a whole new object (calling it statically) and just select the few methods I need from the class?
Do I have that right?
There are no significant performance benefits to using either approach, especially on a production server with byte code cache.
Method chaining is just a shorter way of writing things. Compare with the longer version:
$foo = Bar::get('sysop');
$foo -> set('admin');
$foo -> render();
It does have some quirks, though: a typical IDE (such as Eclipse) can auto-complete your code in the longer version (as long as the type of $foo is known) but needs you to document the return type of all methods to work in the short version.
It still instantiates an object; it's just never assigned to a variable. Basically, you're just calling the methods of an anonymous object.
I think any cycle-savings would be negligible, but I think the unassigned objects would be freed immediately after this line of code, so you may have some memory savings (you could accomplish the same by setting assigned objects to null when you were done with them).
The main reason people use method chaining is for convenience; you're doing a lot in one line of code. Personally, I think it's messy and unmaintainable.
if I don't have to instantiate a whole
new object (calling it statically) and
just select the few methods I need
from the class?
Wrong! To return $this, the class has to be instantiated.

correct use of 'construct' when designing classes

I am new to object oriented programming and writing some of my first classes for a PHP application.
In some of the simpler classes, I declare a function __construct(), and inside of that function, call certain class methods. In some cases, I find myself instantiating the class in my app, and not needing to do anything with the resultant object because the class's __construct() called the methods, which did their job, leaving me nothing left to do with the class.
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Again, I'll stress this is only the case for some of my more simple classes. In the more complicated ones, I do use class methods via the object and outside of __construct().
Do I need to rethink the way I coding things, or am I ok?
Well, the constructor is used to create a new instance of a class, and to do any necessary setup on that class. If you're just creating the class and leaving it, that does seem a bit of a waste. Why not, for instance, use static functions in the class as an organizational tool and just call them(or a function that calls them) instead of constructing a new instance that you'll never use?
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Yes, that should raise a red flag.
In general, you should not let constructors have any side effects; They are meant for initialising the state of the object - not for anything else. There are of course exceptions to this rule, but in general it's a good guide line. You should also abstain from doing any heavy calculations in the constructor. Move that to a method instead.
Side effects are many things - Changes to global variables or static (class) variables; output to the environment (For example calls to print(), header() or exit()); calls to a database or other external service and even changes to the state of other objects.
A side effect free function is also called a "pure" function - as opposed to a procedure, which is a function that has side effects. It's a good practise to explicitly separate pure functions from procedures (and perhaps even label them as such).

Categories