Access Modifiers: Public vs Private
Learn about the public and private access modifiers and how they can be accessed from outside the class.
The public
access modifier
The public
access modifier allows code from both outside and inside the class to access the class’s methods and properties.
How to access a public property
In the following example, the class’s property and method are defined as public
, so the code outside the class can directly interact with them.
Press + to interact
<?phpclass Car {// Public methods and propertiespublic $model;public function getModel(){return "The car model is " . $this -> model;}}$mercedes = new Car();// Here we access a property from outside the class$mercedes -> model = "Mercedes";// Here again we access another method from outside the classecho $mercedes -> getModel();?>
In line 15, we set the public
property $model
...