PHP Class and Objects

Class and objects is a programming template to write a program in a block.

It is helps to developer write complex program in simple way, reuse a program in multiple applications and create a structural program.

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:    

Explanation:

Create a class with “class” keyword then define a class name. The name must start with string or underscore (_).

PHP is a case sensitive language so class name also case sensitive. Means Pen is write word to access this class. start PEN,  pEn, The name not the same.

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

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

Output:

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.