Learn by Doing: Practice PHP OOP (level 3)

If you like this post and want more connect with me on Twitter: Follow @justericchapman

You want to learn PHP OOP for a long time but you keep postponing? Now is the time! For the next 30 days I will post php OOP exercises + solution.

Your challenge …

If you like this post and want more connect with me on Twitter: Follow @justericchapman

You want to learn PHP OOP for a long time but you keep postponing? Now is the time! For the next 30 days I will post php OOP exercises + solution.

Your challenge is to try to solve the small exercise without looking at the solution. You can use the web to search for concept but please dont look at the solution before at least try to solve the exercise.

We will start very easy but don't be bored because exercises will quickly became more and more challenging....

Challenge accepted?

Exercise #5

In exercise #4 we created a class with a constructor using property promotion:

<?php
class Product 
{
    public function __construct(private $name, private $description, private $price) 
    {
    }
}

Today your challenge is to create a getter and setter to modify the name property.

Hint: Getter and Setter are 2 methods:

The getter method is a method that get (return) the object instance property value.

The setter method is setting the current instance property value to a new supply value.

Let's do it!

Exercise #6

A quick one: When setting the property name. Make sure that the name first letter is Uppercase.

Solution:

STOP... Do the exercises first! It's the only way you will really learn.

If you have done your exercise here my solution. Noted most of the times, more than one solution will be possible. If you have something different that me, leave your solution in the comment to share and discuss.

Exercise 5 solution:

class Product
{
    public function __construct(private $name, private $description, private $price) 
    {

    }

    public function setName($name){
        $this->name = $name;
    }

    public function getName(){
        return $this->name;
    }
}

Exercise 6 solution:

public function setName($name){
    $this->name = ucfirst($name);
}

Conclusion

That's it for today. Tomorrow the journey continue, see you later!

If you want to be contribute you can re-tweet this post on tweeter
Follow @justericchapman


Print Share Comment Cite Upload Translate
CITATION GOES HERE CITATION GOES HERE
Select a language: