PHP Class properties


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


 Live Demo

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


The output of above code is as follows −


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


class myclass{
   private string $name;
   private int $age;
   function setdata(string $x, int $y){
$obj=new myclass("Kiran",20);

Updated on: 18-Sep-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started