PHP Class properties

PHPServer Side ProgrammingProgramming

Introduction

Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class. That's why it is sometimes referred as instance variable.

Inside any instance method, property can be accessed by calling object's context available as a pesudo-variable $this. If a property is declared as public, it is available to object with the help of -> operator. If a property is defined with static keyword, its value is shared among all objects of the class and is accessed using scope resolution operator (::) and name of class.

property declaration and access

This example shows how a property is defined and accessed

Example

 Live Demo

<?php
class myclass{
   private $fname="Kiran";
   public $mname="Pratap";
   static $lname="Singh";
   function dispdata(){
      echo "$this->fname\n";
      echo "$this->mname\n";
      echo myclass::$lname;
   }
}
$obj=new myclass();
$obj->dispdata();
?>

Output

The output of above code is as follows −

Kiran
Pratap
Singh

Outside class, instance properties declared as public are available to object, but private properties are not accessible. In previous versions of PHP, var keyword was available for property declaration. Though it has now been deprecated, it is still available for backward compatibility and is treated as public declaration of property.

PHP 7.4 introduces type declaration of property variables

Example

<?php
class myclass{
   private string $name;
   private int $age;
   function setdata(string $x, int $y){
      $this->name=$x;
      $this->age=$y;
   }
}
$obj=new myclass("Kiran",20);
?>
raja
Updated on 18-Sep-2020 11:34:13

Advertisements