Klassen in eine Library definieren und das Ganze über Autoloader (Funktion) einbinden.
Struktur: todo.php
use Todo\Item as TodoItem;
use Todolist\Item as ListItem;
function meinAutoloader($class) {
$newName = str_replace('\\', '/', $class);
$path = "lib/$newName.php";
if (file_exists($path)) {
require $path;
}
}
spl_autoload_register('meinAutoloader');
ini_set('display_errors', true);
$list = new ListItem("Einkauf");
$list->addTodo(new TodoItem("Milch"));
$list->addTodo(new TodoItem("Müsli"));
$list->addTodo(new TodoItem("Bananen"));
$items = $list->getTodos();
foreach ($items as $item) {
echo $item->getTitle() . "<br>";
}
Struktur: lib/Todo/Item.php
namespace Todo;
class Item
{
private $_title;
public function __construct(string $title)
{
$this->_title = $title;
}
public function getTitle()
{
return $this->_title;
}
}
lib/Todo/Db/Adapter.php
namespace Todo\Db;
class Adapter {
}
Struktur: lib/Todolist/Item.php
namespace Todolist;
use Todo\Item as TodoItem;
class Item {
private $name = "";
private $todoItems = array();
public function __construct(string $name)
{
$this->name = $name;
}
public function addTodo(TodoItem $item) {
$this->todoItems[] = $item;
}
public function getTodos() {
return $this->todoItems;
}
}