1

I have three classes DatabaseHandler, MainPage, and Form

DatabaseHandler.php

class DatabaseHandler extends DatabaseConnection
{

}

MainPage.php

require 'DatabaseHandler.php'
class MainPage
{

}

Form.php

require 'DatabaseHandler.php'
class Form
{

}

on this util.php file it throws an error "cannot redeclare class"

//util.php
require 'MainPage.php';
require 'Form.php';

how can I avoid this error, i searched before and it says that the only solution is "namespace", i tried reading about it but Im confused and i dont know how to apply it on my situation.

tereško
  • 58,060
  • 25
  • 98
  • 150
Beginner
  • 1,700
  • 4
  • 22
  • 42
  • 4
    use `require_once` instead of `require`. This has nothing to do with namespaces. You're just importing `DatabaseHandler.php` twice. – Federico klez Culloca Jun 13 '18 at 07:16
  • 2
    Possible duplicate of [PHP Fatal error: Cannot redeclare class](https://stackoverflow.com/questions/708140/php-fatal-error-cannot-redeclare-class) – Nigel Ren Jun 13 '18 at 07:17
  • @FedericoklezCulloca that a terrible advice. This should be solved using autoloader, instead of manually wiring the class-files. – tereško Jun 13 '18 at 07:35
  • @tereško can you please explain why it's "terrible" (a link would be enough)? I mean, "not the best way to do it" or "not best practice" I wouldn't even ask. But "terrible"? – Federico klez Culloca Jun 13 '18 at 07:38
  • For someone just starting out, the advice is good. One step at a time. – Willem Renzema Jun 13 '18 at 07:51
  • @FedericoklezCulloca it leads to what one could describe as "include oriented programming". It basically a way to ruin a beginner. – tereško Jun 13 '18 at 07:54

1 Answers1

0

The util.php requires the MainPage.php and Form.php.

Use require_once 'DatabaseHandler.php' instead of require 'DatabaseHandler.php'.

This should work!