Search⌘ K
AI Features

Solution Review: Dependency Injection

Learn how to enhance PHP code by applying dependency injection and namespaces. This lesson guides you through creating classes with constructors, using type hinting, and defining interfaces to manage dependencies effectively.

Solution: Task 1

PHP
<?php
class Article {
protected $title;
protected $author;
public function __construct($title, $author) {
$this -> title = $title;
$this -> author = $author;
}
public function getTitle() {
return $this -> title;
}
public function getAuthor() {
return $this -> author;
}
}
class Author {
protected $name;
public function setName($name) {
$this -> name = $name;
}
public function getName() {
return $this -> name;
}
}
function test()
{
$author1 = new Author();
$author1 -> setName("Joe");
$title = "To PHP and Beyond";
$article1 = new Article($title,$author1);
return $article1 -> getTitle() . ' by ' . $article1 -> getAuthor() -> getName();
}
echo test();
?>

Explanation

  • Line 2: We write the Article class with protected properties $title and $author.
  • Line 6: We add the __construct() method to the Article class, which gets two parameters and sets the values of $title and $author properties.
  • Line 11: We add the getTitle() getter method to the Article class, which returns the $title
...