Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>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.</p> <p>Consider a simple class that encapsulates a string and has a method that returns the length of this string. One possible implementation would be:</p> <pre><code>class StringWrapper { private $str; public function setInnerString($str) { $this-&gt;str = (string) $str; } public function getLength() { if ($this-&gt;str === null) throw new RuntimeException("Invalid state."); return strlen($this-&gt;str); } } </code></pre> <p>In order to be in a valid state, this function requires <code>setInnerString</code> to be called before <code>getLength</code>. By using a constructor, you can force all the instances to be in a good state when <code>getLength</code> is called:</p> <pre><code>class StringWrapper { private $str; public function __construct($str) { $this-&gt;str = (string) $str; } public function getLength() { return strlen($this-&gt;str); } } </code></pre> <p>You could also keep the <code>setInnerString</code> to allow the string to be changed after instantiation.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload