Classes and Objects

Getting Started with PHP
Getting Started with PHP : Home
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Object Interfaces
Static and Final
Advanced Features in PHP
Session in PHP
Cookies in PHP
Server Variables

Classes are used to create user customized data structures. A class is only a structure and does not contain any data. It can't be used as a variable and operations can't be performed. For doing all that we need to create an instance of that class called object. For understanding assume car is class and a particular car is a object.
Classes are defined in PHP with class followed by name of class. A class have it's properties (variables) and methods (functions).

 class sample

Object is an instance of class. It's possible to create as many objects of a class as you want.
An object is created using the new keyword followed by classname().

 $object = new classname();

The variables of class are known as its properties or attributes. These attributes are accessed using -> ($object->property).
Always remember you don't need to use the $ before property name (variable) while accessing with ->.
You can have constants in a class i.e. it will not change value holded by it. Constants do not use $ and declared using const keyword and accessed using :: (Scope Resolution Operatoer).

The member function of class are the methods of that class. Methods are called using the same way as properties (-> Operator).

We will access properties and call functions for an object not class (except for static variables and methods). All the changes made will also be for that object and other objects will remain unaffected.

$this is used inside class while referencing its member properties or methods.

Visibility of Properties and Methods
You can control the access of the properties and methods while calling from outside using the keywords public, private, protected.

 class myclass{
 	public $pub = "Public";
 	private $pri = "Private"; // Properties of Attributes

 	public function showproperties(){
 		echo "From inside\n";
 		echo $this->pub."\n".$this->pri; //Accessing properies from
 		                                //inside using $this

$object = new myclass();   // Creating Object
$object->showproperties();   // Calling method

echo "<br>From Outside\n";
echo $object->pub."\n";
echo @$object->pri;   //@ is to ignore error 


From inside Public Private
From Outside Public

As you can see, private member was not to accessed from outside the class. We used @ to avoid error given by $object->pri from outside of the class.

Login to Track Your Progress