⊗ppOpBsPG 12 of 107 menu

Property Getters in OOP in PHP

Let's say we have the following class with private properties:

<?php class User { private $name; private $surn; public function __construct($name, $surn) { $this->name = $name; $this->surn = $surn; } } ?>

As you can see, these properties are set once when the object is created. However, now these properties cannot be read, because they are private and there are no corresponding methods for this.

Let's create special methods for our properties that allow reading these properties. Such methods (they are called getters) usually start with the word get, followed by the name of the property being read.

Let's create getters for our properties:

<?php class User { private $name; private $surn; public function __construct($name, $surn) { $this->name = $name; $this->surn = $surn; } public function getName() { return $this->name; } public function getSurn() { return $this->surn; } } ?>

Let's test their work. Let's create an object, passing the user data as parameters:

<?php $user = new User('john', 'smit'); ?>

Let's read this data using the getters:

<?php var_dump($user->getName()); var_dump($user->getSurn()); ?>

In the Employee class, create three private properties: name, salary and age.

Pass the values of these properties as constructor parameters.

Create getters that output the values of each of our properties.

byenru