OOP Namespacing

Home Forums Bugs OOP Namespacing

Tagged: 

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1392
    jurgenmuca
    Participant

    Fatal error: Cannot declare class book, because the name is already in use

    Cannot declare 2 classes with the same name in the same file

    Fix: use different files

    include ‘cbook.php’;

    Fatal error: Cannot declare class book, because the name is already in use in C:\xampp\htdocs\OOPtutorial\cbook.php on line 3

    Cannot use the same name for classes even if they are on different files if used with include

    Fix: Use namespaces

    namespace App\Library;
    class book{

    }

    Fatal error: Uncaught Error: Class “book” not found

    include ‘cbook.php’;

    $library = new book();

    Even if there are classes named book in cbook.php we still need to specify the namespace

    include ‘cbook.php’;

    $library = new book();

    Fix: at class declaration: namespace\classname

    $library = new App\Library\book();

    Namespace: App\Library

    Class: book()

     

    Fatal error: Cannot use App\Library\book as book because the name is already in use

    include ‘cbook.php’;
    class book{
    function __construct()
    {
    echo “From index <br>”;
    }
    }

    use App\Library\book ;

    $book = new book();

    To fix, the imported class from the namespace:

    use App\Library\book;

    can have a different class name.

    Fix:

    use App\Library\book as bookFromLibrary;

    $book = new book();
    $book = new bookFromLibrary();

     

     

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.