Purpose of PHP constructors

后端 未结 6 1722
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 20:14

I am working with classes and object class structure, but not at a complex level – just classes and functions, then, in one place, instantiation.

As to __const

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 20:28

    The constructor of a class defines what happens when you instantiate an object from this class. The destructor of a class defines what happens when you destroy the object instance.

    See the PHP Manual on Constructors and Destructors:

    PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

    and

    PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. 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.

    In practise, you use the Constructor to put the object into a minimum valid state. That means you assign arguments passed to the constructor to the object properties. If your object uses some sort of data types that cannot be assigned directly as property, you create them here, e.g.

    class Example
    {
        private $database;
        private $storage;
    
        public function __construct($database)
        {
            $this->database = $database;
            $this->storage = new SplObjectStorage;
        }
    }
    

    Note that in order to keep your objects testable, a constructor should not do any real work:

    Work in the constructor such as: creating/initializing collaborators, communicating with other services, and logic to set up its own state removes seams needed for testing, forcing subclasses/mocks to inherit unwanted behavior. Too much work in the constructor prevents instantiation or altering collaborators in the test.

    In the above Example, the $database is a collaborator. It has a lifecycle and purpose of it's own and may be a shared instance. You would not create this inside the constructor. On the other hand, the SplObjectStorage is an integral part of Example. It has the very same lifecycle and is not shared with other objects. Thus, it is okay to new it in the ctor.

    Likewise, you use the destructor to clean up after your object. In most cases, this is unneeded because it is handled automatically by PHP. This is why you will see much more ctors than dtors in the wild.

提交回复
热议问题