Private Properties in OOP in PHP
Object properties that can be read and written from outside are called public. There are also private properties, which will be accessible only inside the class.
Private property names must be
declared with the access modifier private
.
Let's do this:
<?php
class User {
private $name;
}
?>
Now let's write data to our property. This can be done, for example, in the class constructor:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
}
?>
Now let's create a method that will return the value of our property:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->name;
}
}
?>
Let's create an object of the class, passing the user name as a parameter:
<?php
$user = new User('john');
?>
An attempt to directly access our property outside the class will result in an error:
<?php
echo $user->name; // error
?>
And calling our method will allow reading this property:
<?php
echo $user->show(); // will output 'john'
?>
In the Employee
class, create
three private properties: name, salary,
and age.
Pass the values of these properties as constructor parameters.
Create a method that will output the employee's data.