PHP Class Properties

Description

Class properties are very similar to variables.

An object's property can store a single value, an array of values, or even another object.

Syntax

To add a property to a class, first write the keyword public, private, or protected, followed by the property's name preceded by a $symbol.

public, private, or protected are the visibility levels you want to give to the property:


class MyClass { /*from ww w.  j  a  v  a 2  s.co m*/
    public $property1;     // This is a public property 
    private $property2;    // This is a private property 
    protected $property3;  // This is a protected property 
}   
We can initialize properties at the time that we declare them:
 
class MyClass { 
  public $value = 123; 
}  

Accessing Properties

We can access the corresponding object's property value from within your calling code by using the following syntax:

$object->property;

Write the name of the variable storing the object, followed by an arrow symbol composed of a hyphen (-) and a greater - than symbol (>), followed by the property name.

Note that the property name doesn't have a $ symbol before it.

Example

We can add properties to a class.


<?PHP/*w  w  w .  ja  v a 2 s . com*/
class Shape{
   public $Name;

   public function say() {
       print "shape";
   }
}
$aRectangle = new Shape;
$aRectangle->say();
$aRectangle->Name = "Rect";
$aRectangle->say();
?>

The code above generates the following result.

-> is used to work with the property, and also that there is no dollar sign before Name.

Each object has its own set of properties. Consider the following code:


<?PHP/*from www  . ja v  a2s. co  m*/
class Shape{
   public $Name;

   public function say() {
       print "shape";
   }
}
class Rectangle extends Shape{
}


$aRect = new Rectangle;
$bRect = new Rectangle;
$aRect->Name = "A";
$bRect->Name = "B";
print $aRect->Name;
print $bRect->Name;
?>

PHP allows you to dynamically declare new properties for objects. It would create the property only for the object, and not for any other instances of the same class.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition