PHP Class Properties
In this chapter you will learn:
- Creating and Using Properties
- Declaring Properties
- Accessing Properties
- Example - add properties to a class
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 j ava2s. c o 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//from ja v a 2 s .c om
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//jav a 2s . c o 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.
Next chapter...
What you will learn in the next chapter: