Purpose of PHP constructors?

A constructor is a function that is executed after the object has been initialized (its memory allocated, instance properties copied etc. ). Its purpose is to put the object in a valid state Frequently, an object, to be in an usable state, requires some data. The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data Consider a simple class that encapsulates a string and has a method that returns the length of this string.

One possible implementation would be: class StringWrapper { private $str; public function setInnerString($str) { $this->str = (string) $str; } public function getLength() { if ($this->str === null) throw new RuntimeException("Invalid state. "); return strlen($this->str); } } In order to be in a valid state, this function requires setInnerString to be called before getLength By using a constructor, you can force all the instances to be in a good state when getLength is called: class StringWrapper { private $str; public function __construct($str) { $this->str = (string) $str; } public function getLength() { return strlen($this->str); } } You could also keep the setInnerString to allow the string to be changed after instantiation A destructor is called when an object is about to be freed from memory. Typically, it contains cleanup code (e.g. Closing of file descriptors the object is holding).

They are rare in PHP because PHP cleans all the resources held by the script when the script execution ends.

A constructor is a function that is executed after the object has been initialized (its memory allocated, instance properties copied etc. ). Its purpose is to put the object in a valid state. Frequently, an object, to be in an usable state, requires some data.

The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data. Consider a simple class that encapsulates a string and has a method that returns the length of this string. One possible implementation would be: class StringWrapper { private $str; public function setInnerString($str) { $this->str = (string) $str; } public function getLength() { if ($this->str === null) throw new RuntimeException("Invalid state.

"); return strlen($this->str); } } In order to be in a valid state, this function requires setInnerString to be called before getLength. By using a constructor, you can force all the instances to be in a good state when getLength is called: class StringWrapper { private $str; public function __construct($str) { $this->str = (string) $str; } public function getLength() { return strlen($this->str); } } You could also keep the setInnerString to allow the string to be changed after instantiation. A destructor is called when an object is about to be freed from memory.

Typically, it contains cleanup code (e.g. Closing of file descriptors the object is holding). They are rare in PHP because PHP cleans all the resources held by the script when the script execution ends.

Another way of saying "put the object in a valid state" is to say "ensure the objects invariants are true. " The invariants of the class are the facts should always be true about the instances: like the inner str value should always be initialised. – Oddthinking Jun 13 '10 at 17:37.

Because instead of: $person = new Person(); $person->name='Christian'; $person->surname='Sciberras'; you can use: $person = new Person('Christian','Sciberras'); Which is less code and looks cleaner! Note: As the replies below correctly state, constructors/destructors are used for a wide variety of things, including: de/initialization of variables (especially when the the value is variable), memory de/allocation, invariants (could be surpassed) and cleaner code. I'd also like to note that "cleaner code" is not just "sugar" but enhances readability, maintainability etc.

Apart from the doubtful use of public properties, I think this answer misses the point. Constructors are not mere syntactic sugar as it seems to be implied, they are a way to enforce invariants. – Artefacto Jun 13 '10 at 16:25 3 It doesn't only look cleaner.It prevents errors: What happens if you forget to set surname?

The constructor forces you to do it. – johannes Jun 13 '10 at 16:26 The OP ask for a real-life example, and I showed one. The use of public properties is so that the example is functional for both cases.

My answer does not miss any point. The constructor can be used for anything (including what you mentioned) to set default variables. Quick example: class A { protected $path; public function __construct(){ $this->path=getcwd().

'path'; } } – Christian Sciberras Jun 13 '10 at 16:48.

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.

Ok sorry , assume for example , cache basic purpose is increase site performance , even I can monitor this cache concept, also we can show real time like while exacuting query on that time in one file we copy the records and next time user trying to hit records, then system will look only file not an live DB, is there any thing like you can give example,please – Bharanikumar Jun 13 '10 at 16:04 @Bharanikumar that's a completely different question than what you are asking above. If you need a Cache, look into APC or memcache and study some code examples, like Zend_Cache. – Gordon Jun 13 '10 at 16:08 actually I know cache .

No no...to understand easily can some one say example like cache, this waht I asked, but now I got lot examples also, – Bharanikumar Jun 13 '10 at 16:15.

The constructor is run at the time you instantiate an instance of your class. So if you have a class Person: class Person { public $name = 'Bob'; // this is initialization public $age; public function __construct($name = '') { if (!empty($name)) { $this->name = $name; } } public function introduce() { echo "I'm {$this->name} and I'm {$this->age} years old\n"; } public function __destruct() { echo "Bye for now\n"; } } To demonstrate: $person = new Person; $person->age = 20; $person->introduce(); // I'm Bob and I'm 20 years old // Bye for now We can override the default value set with initialization via the constructor argument: $person = new Person('Fred'); $person->age = 20; $person->introduce(); // if there are no other references to $person and // unset($person) is called, the script ends // or exit() is called __destruct() runs unset($person); // I'm Fred and I'm 20 years old // Bye for now Hopefully that helps demonstrate where the constructor and destructor are called, what are they useful for? __construct() can default class members with resources or more complex data structures.

__destruct() can free resources like file and database handles. The constructor is often used for class composition or constructor injection of required dependencies.

Ive found it was easiest to grasp when I thought about the new keyword before the constructor, it simply tells my variable a new object of its data type would be give to him, based on which constructor I call and what I pass into it, I can define to state of the object on arrival. Without the new object, we would be living in the land of null, and crashes! The Destructor is most obvious from a C++ stand point, where if you don't have a destructor method delete all the memory pointed to, it will stay used after the program exits causing leaks and lag on the clients OS untill next reboot.Im sure theres more than enough good information here, but a nother angle is always helpful from what Ive noticed!

About the leak part, it is not accurate. When you exit your program, any leak is removed (unless the memory resides in another program). Memory leaks are bad mostly during the use of the program, not when it exits.

For example, I've once had a program which leaked 700Mb in 1hr of use. But when closed everything returned to normal. – Christian Sciberras Jun 18 '10 at 10:42.

Its purpose is to put the object in a valid state. Frequently, an object, to be in an usable state, requires some data. The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data.

Consider a simple class that encapsulates a string and has a method that returns the length of this string. In order to be in a valid state, this function requires setInnerString to be called before getLength.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions