- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Class properties
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
<?php 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(); ?>
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); ?>