Each property of a class in PHP can have one of three visibility levels, known as public, private, and protected:
Level | Meaning |
---|---|
Public properties | can be accessed by any code, whether that code is inside or outside the class. |
Private properties | can be accessed only by code inside the class. |
Protected properties | like private properties in that they can't be accessed by code outside the class, any class that inherits from the class can also access the properties. |
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:
class MyClass { public $property1; // This is a public property private $property2; // This is a private property protected $property3; // This is a protected property }
You can initialize properties at the time that you declare them, much like you can with variables:
class MyClass { public $myValue = 123; }
In this case, whenever a new object is created from MyClass, the object's $myValue property defaults to the value 123.