Class and objects is a programming template to write a program in a block.
It
A class has two member one Variables and two Functions. A class is a program structure where developer defines application logic.
Object is a way which use to access class. Create an object developer access their application logic which defines in a class anywhere in a project.
Class and Object is a very useful and easy way to create a complicated application in a simple way.
Creating Class:
1 2 3 4 5 6 7 8 9 | <?php class Pen{ var $name = “Ink”; var $price = 25; function describe(){ echo “I am a pen Class”; } } ?> |
Explanation:
Create a class with “class” keyword then de
PHP is a
Between { } define whole logic or code. Variable must be declared with var keyword or public keyword and all logic operation must be defined in function.
Creating Object
1 2 3 4 5 6 7 8 9 10 11 | <?php class Pen{ var $name = “Ink”; var $price = 25; function describe(){ echo “I am a pen Class”; } } $obj = new Pen; echo gettype($obj); //gettype() return the data-type of a variable ?> |
Explanation:
new keyword create object of a class. Object has authority to access the class variable and function out of the class.
In this example $obj is an object of Pen class, $obj can access $name, $price or can call the describe() function out of the class.
Object never creates within class.
Accessing Members and Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class Fruit{ var $name = “Banana”; var $price = 200; function describe(){ echo “The bucket is full of”.$this->name.” and price of this bucket is ”.$this->price; } } $obj = new Fruit; $obj->describe(); echo “<br>”; echo $obj->name; echo “<br>”; echo $obj->price; ?> |
Output:
1 2 3 | The bucket is full of Banana and price of this bucket is 200 Banana 200 |
Explain:
Accessing class member variable and function by object. “->” this is accessing symbol.
$this variable is use to access class member variable in to the class member function. $this is object pointer, with reference an instance of class.