How to Declare a class in php and use it

Declare a class

1
2
3
4
class SimpleClass
{
  //Class body like properties and method goes here
}

We can declare a class using the keyword class.A Class name can start with a underScore or we can start with letter.In the Upper example SimpleClass is the Class Name.We can also Declare this class as _SimpleClass.

 

Add properties inside a class

class SimpleClass
{
   // property declaration
   public $var = 'you are at waytocode.com';
}

There are 3 types of access specifier in OOPs Concept.

  • Private
  • public
  • protected

In the previous code am telling about the public access specifier. As we are declaring variables in normal php ,we did the same as writing as

public $var; .Remember in php the default access specifier is public where in c++ its private. After defining the variable we need to initialize the variable as adding some content to it as public $var =’you are at waytocode.com’;.

 

Add Method inside a class

class SimpleClass
{
   // property declaration
   public $var = 'you are at waytocode.com';
 
   // method declaration
   public function displayVar()
   {
       echo $this->var;
   }
}

initialize a object of a declared Class

1
2
3
$object = new SimpleClass;
//Or we can also declare the class as below too
$object = new SimpleClass();

To Use a Class we need to first create a Object of Class.We can create Object using new keyword. In the Previous Code , $object is a object of Class with name as SimpleClass.$object is a instance of class .

 

Use Object of a Class

$object->displayVar();

It will output as you are at waytocode.com.

 

Complete Code

1
2
3
4
5
6
7
8
9
10
class SimpleClass
{
  public $var = 'you are at waytocode.com';
  public function displayVar()
  {
    echo $this->var;
  }
}
$object = new SimpleClass();
$object->displayVar();