Showing posts with label constructor. Show all posts
Showing posts with label constructor. Show all posts

Friday, 25 October 2013

OOP Series : Constructors and destructors

In OOP, constructors are initialisers and destructors are clean up operations.
In the case of PHP you declare a constructor of your class. It will be run when an object is created from the class. You can also declare a destructor which will be "called as soon as there are no other references to a particular object, or in any order during the shutdown sequence."
In the case of JavaScript, you don't have a specific method, but just make all your declarations.
In JavaScript, it's best to rely upn the garbage collector.
class familyphoto
public $mywidth, $myheight;
function __construct($mywidth = NULL, $myheight = NULL)
$this->mywidth = $mywidth;
$this->myheight = $myheight;

function __destruct()
$this->mywidth = NULL;
$this->myheight = NULL;
familyphoto = function(mywidth, myheight)
this.mywidth = typeof mywidth !== 'undefined' ? mywidth : null;
this.myheight = typeof myheight !== 'undefined' ? myheight : null;
Now a file (index.php) which creates 2 objects from both. In one, passing no values, and in another, passing 2 required values.
require_once 'familyphoto.class.php';
$familyphoto1 = new familyphoto;
echo $familyphoto1->mywidth.'<br />';
echo $familyphoto1->myheight.'<br />';
$familyphoto2 = new familyphoto(4,3);
echo $familyphoto2->mywidth.'<br />';
echo $familyphoto2->myheight.'<br />';

<script src="familyphoto.class.js"></script>
var familyphoto1 = new familyphoto();
document.write(familyphoto1.mywidth+'<br />');
document.write(familyphoto1.myheight+'<br />');
var familyphoto2 = new familyphoto(4,3);
document.write(familyphoto2.mywidth+'<br />');
document.write(familyphoto2.myheight+'<br />');