Challenge: Dependency Injection

Try to solve the dependency between classes using dependency injection and type hinting.

Since these problems are designed for your practice, try to solve them yourself first. If you get stuck, you can click the “Show Solution” button to see how the problem can be solved. Good luck!

Task 1

Write an Article class that is dependent on an Author class and introduce the Author object through dependency injection into the constructor.

  • Write the Article class with $title for the title of the article, and $Author to hold the author object.
  • Add a constructor method to the Article class that gets the parameters of $title and $author and sets the class’s properties accordingly.
  • Write a getter method that returns the article’s title.
  • Add a getter method that returns the Authorobject.
  • Write another class named Author that has a protected property $name and setter and getter methods that handle the property.
  • Now in the test() method, create an Author object, name it $author1, and then set its name to Joe.
  • Create the Article object, call it $article1, and name it To PHP and Beyond and the $author1 object that you’ve just created.

Expected output

Write code that returns the following string:

To PHP and Beyond by Joe

Coding exercise

Get hands-on with 1400+ tech skills courses.