⊗ppOpBsPr 3 of 107 menu

Properties of Objects in PHP

Now we will learn to work with objects and their properties using a more practical example. Let's create a User class that will describe a user of our site. Let our user have two properties: name and age. Let's write the code for our class:

<?php class User { public $name; public $age; } ?>

So far, our class doesn't do anything - it simply describes what objects of this class will have (in our case, each object will have a name and an age). Essentially, until we create at least one object of our class - nothing useful will happen.

Let's create an object of our class. In doing so, keep in mind that it is customary to name classes with capital letters, and objects of these classes with lowercase letters.

Let's declare the class:

<?php class User { public $name; public $age; } ?>

And now let's create an object of our class:

<?php $user = new User; ?>

Now let's write something into the properties of our object, and then output this data to the screen:

<?php $user = new User; $user->name = 'john'; $user->age = 25; echo $user->name; echo $user->age; ?>

Make a Employee class, in which there will be the following properties - name, age, salary.

Create an object of the Employee class, then set its properties to the following values - name 'john', age 25, salary 1000.

Create a second object of the Employee class, set its properties to the following values - name 'eric', age 26, salary 2000.

Output the sum of the salaries of the created employees.

Output the sum of the ages of the created employees.

byenru