Oct
15
2008

OOP: Instantiation

Instantiation, is another complex word meaning creating an object. DYK: At first PHP wasn’t a OOP language!

A CLASS is a package containing two things: data and methods. Methods are just functions within a class, they obviously change name to make it more complex.The data portion consists of variables; they’re known as properties. The other part of a class is a set of functions that can alter a class’ properties; they’re called methods.

Remember that Objects can be parents, and allow their children to access parts of its contents.This is called inheritance and is one of the major advantages of classes over functions

Class Facts
- Classes always passed by reference(no need for &$class)
- Objects can have parents and children.
- Methods = Functions
- Use -> to initiate method within class or ::

Declaring a Class:

class myclass {
//class contents
}

Instantiating an Object

$theclass = new myclass();

Its as easy as that, if you want to do something to the class then you simply use $theclass now.

Hello World - Object Instantiation

As you are aware the first thing any developer does in a new language is write hello world:

Class say {
   function helloWorld(){
      echo "Hello world!";
   }
   function helloMum(){
      echo "Hello Mum!";
   }
}
$myObject = new say();
$myObject->helloworld();

As you can see we create a class called say, and they have two functions one called hello world and one called hello mum. When we close the object it is called by “new say()” we then use “->” to ask the object to run method (function) hello world.
The expected output for this will be “Hello World” it wont be “Hello World, Hello Mum” as that would be embarising ! but mainly because it was not called.

Calling a Method/Function or Variable/Content

If you have a method or function in a object you can call it using-> or :: here are examples:

Class say {
var $test = "testing";
 
   function helloworld(){
      echo "Hello world!";
   }
}
 
say::helloworld(); //Output Hello World
$myObject = new say(); // Inititalise Object
echo $myObject->test; //Output Testing
$myObject->helloworld(); //output Hello World

It works out you can use :: without even initialising the object! that’s something i did not know.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 04. Object Oriented Programming | Tags:

1 Comment »

  • lekshmy

    it is good but needs more explanation regarding memory allocation while creating an object

    Comment | December 23, 2008

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS