PHP provides three keywords for controlling the scope of properties and methods:
-
public- These properties are the default when declaring a variable using thevarorpublickeywords, or when a variable is implicitly declared the first time it is used. The keywordsvarandpublicare interchangeable because, although deprecated, var is retained for compatibility with previous versions of PHP. Methods are assumed to be public by default. -
protected- These properties and methods (members) can be referenced only by the object's class methods and those of any subclasses. -
private- These members can be referenced only by methods within the same class—not by subclasses.
To help you to decide which you need to use:
- Use
publicwhen outside code should access this member and extending classes should also inherit it. - Use
protectedwhen outside code should not access this member but extending classes should inherit it. - Use
privatewhen outside code should not access this member and extending classes also should not inherit it.
To demonstrate these modifiers, take a look at the following example:
<?php
class Car {
// These are the class properties
public $name;
protected $country;
private $model;
}
$car = new Car();
$car->name = 'Ford';
$car->country = 'USA';
$car->model = '1995';
The result shows that protected and private properties of the object is not accessible and PHP returns an error.