PHP Basics of Class and Object

PHPServer Side ProgrammingProgramming

Introduction

Class is a user defined data type in PHP. In order to define a new class, PHP provides a keyword class, which is followed by a name. Any label that is valid as per PHP's naming convention (excluding PHP's reserved words) can be used as name of class. Constituents of class are defined in curly bracket that follows name of class

Syntax

class myclass{
   //
}

Class may contain constants, variables or properties and methods - which are similar to functions

Example of class

This example shows how a Class is defined

Example

<?php
class myclass{
   const MYCONSTANT=100;
   public $var1="Hello";
   function dispvar(){
      echo $this->var1;
   }
}
?>

Function defined inside class is called method. Calling object's context is available inside a method with a pseudo-variable $this. If method is defined as static, it is accessed with name of class. Calling a non-static method statically has been deprecated in PHP 7

The new operator declares a new object of given class. ame of class followed by paentheses should be mentioned in front of new keyword. An uninitialized object (or with default values to properties) is created if there are no arguments inside parentheses. If class provides definition of constructor with parameters, matching number of arguments must be given. Class must be defined before creating instance (or object)

Example

 Live Demo

<?php
class myclass{
   const MYCONSTANT=100;
   public $var1="Hello";
   function dispvar(){
      echo $this->var1;
   }
}
$obj=new myclass();
$obj->dispvar();
?>

Output

This will produce following result. −

Hello
raja
Published on 18-Sep-2020 13:17:28
Advertisements