Pages

Translate

Wednesday, 23 January 2013

Tutorial1.3:Object(Adding a Method AND Property)



   
  A class isn't particularly useful if it isn't able to do anything,so let look at how you can create a method. Remember that a method of a class is basically just a function. By coding a function inside the braces of your class,you are adding a method to that class. Here is an example:





<?php

class Demo{

function sayHello(){

print "Hello Apple!";

}



}

$obj=new Demo(); //create a object

$obj->sayHello(); // access a function of the object :$obj

?>



Output:



Hello Apple









Adding a property to your class is just as easy as adding a method. You simply declare a variable inside the class to hold the value of the property. In procedural code,when you want to store some value,you assign that value to a variable .In OOP,when you want to store the value of a property,you also use a variable. This variable is declared at the top of the lass declaration,inside the braces that bracket the class's code .The name of variable is the name of property. If the variable is called $name,you will have a property called name.



<?php

class Demo{

public $name;

function sayHello(){

print " Hi! $this->name ";

}



}

$obj=new Demo(); //create a object

$obj->name="Billy";//assign a value to property:name

$obj->sayHello(); // access a function of the object :$obj

?>



Output:



Hi! Billy


No comments:

Post a Comment