Creating a constructor in PHP class

Sometimes you need to initialize class object before call them. So before using our object we can initialize our object using PHP constructor. PHP constructor just initialize object, not allocate object. To allocate object we use new keyword.

Step to write constructor:

Write function then writes double underscore __ and then write name constructor.   See the example below

function __constructor()
{
}

Constructor body is enclosed by curly braces.

Now we write a constructe for Myclass

<?php
class Myclass{
function __constructor()
{
echo “This is PHP constructor”;
}
}
$obj=new Myclass();
?>

See the output. One important thing that in this class we just create a new object of this class but it print “This is PHP constructor”  because we initialize object before use. 

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP