OOPS in PHP 5 - Declaring Class and Initializing Class Object

In Object Oriented Programming Classes is the main entity and all other features of OOP work around the Classes. In this tutorial we will be discussing on declaring class in PHP5. Also covered on how to instantiate the class object.
Declaring Class in PHP5:
In PHP5 you create a new class using “class” keyword.





The basic declaration of a class:

class newClass
{
   public function getAge()
   {
      echo "Inside Method";
   }
}

Here the PHP compiler will allocate the memory for the newClass depending upon the methods, data members defined inside the class.

Initializing an Class Object in PHP5
To access the class from the outside world i.e. outside the scope of class; you will need to create an object instance of the class. This can be achieved using “new” operator.
Example 1 - Initializing Class

class newClass
{
   public function getAge()
   {
      echo "Inside Method";
   }
}     
$newClassInstance = new newClass();

In this case $newClassInstance will point to the object of newClass

Example 2 - Other way to Initialize Class

class newClass
{
   public function getAge()
   {
      echo "Inside Method";
   }
}     
$newClassInstance = new newClass;

This would still have $newClassInstance will point to the object of newClass. But in OOP approach while creating class object the classname should have opening and closing round bracket. This approach of creating class object without brackets will not work in .Net, Java and C++.

Example 3 - Instanciating Class

class newClass
{
   public function getAge()
   {
      echo "Inside Method";
   }
}
$newClassInstance = new myClass();
$newClassInstance1 = $newClassInstance;
unset($newClassInstance);
$newClassInstance1->getAge();

This also is a classic example of the bug in the OOPS implementation in PHP5. This code will work properly as you have unset the $newClassInstance variable and not $newClassInstance1 and both the variables have the separate instance of the object.
Happy Programming on OOPS in PHP5 :)

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)