PracticeMagic methods and constants unveiled

Practice: Magic methods and constants

In the "Magic methods and constants unveiled" tutorial, we learned how and when to use magic methods and constants. We also learned about the use of constructors to set the values of properties as soon as we create objects out of classes.

In the following section, we will be practicing what we learned by writing a simple code that uses magic methods and constants.

Let's practice what we have just learned

* Press on the "solution button" to see our suggested solution.

Let’s return to the User class that we developed in the previous tutorials. However, instead of using setter methods, we will set the values for the first and last name through the constructor.

This is the user class with the private properties of $firstName and $lastName:

class User {
  private  $firstName; 
  private $lastName; 
}

Add to the class a constructor method to set a value to the $firstName property as soon as the object is created.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

So far in the tutorial, we have used the constructor method to set the value of a single property, but we can use a constructor in order to set the values of more than one property. In our exercise, we will use the constructor method to set the value of the $firstName as well as the $lastName.

Add to the constructor the ability to set the value of the $lastName property as well as the $firstName property.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Add to the class a getFullName() public method that returns the full name.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create a new object, $user1, and pass to the constructor the values of the first and last name.
The first name is "John" and the last name is "Doe" (you may choose your preferred combination of first and last name).

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Get the full name, and echo it to the screen.

Expected result:
John Doe

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code
comments powered by Disqus