Fatal error: Cannot declare class orders\order, because the name is already in use in /var/www/html/PHP-and-MySQL-Web-Development/Chapter06/namespaces-pag-196/orders.php on line 4

namespace orders;

class order {
    //
}

class orderItem {
    //
}
include 'orders.php';
$myOrder = new orders\order();

the second example

namespace orders;
include 'orders.php';
$myOrder = new order();

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in /var/www/html/PHP-and-MySQL-Web-Development/Chapter06/namespaces-pag-196/orders.php on line 16

    My wild guess: are you doing include 'orders.php'; from inside of orders.php? If so, don't: you only need to include a file if it's separate from the one you're currently in. In the second example, that would lead to an infinite loop of including the file, which executes that code, which includes itself, which executes the code, which...eventually runs out of memory. In the first example, it could be similar, in that during the initial execution, you create those (namespaced) classes, but then try to create them again on the self-include.

    Generally for "normal" use where you have a class defined in one file and want to use it in a second file, in that second file you do include_once (or probably better: require_once), so that it only includes that file if it has not yet done so.

    I found this example in https://www.w3schools.com/php/php_namespaces.asp
    orders.php

    <?php
    namespace orders;
    class order {
        public $title = "";
        public $numRows = 0;
    
        public function message() {
            echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
        }
    }
    
    class orderItem {
        public $numCells = 0;
        public function message() {
            echo "<p>The row has {$this->numCells} cells.</p>";
        }
    }
    ?>

    index.php

    <?php
    include "orders.php";
    
    $table = new orders\order();
    $table->title = "My table";
    $table->numRows = 5;
    
    $row = new orders\orderItem();
    $row->numCells = 3;
    ?>
    
    <html>
    <body>
    
    <?php $table->message(); ?>
    <?php $row->message(); ?>
    
    </body>
    </html>

    bertrc
    <?php
    include "orders.php";

    Better would be:

    <?php
    require_once "orders.php";
    
    • "require" instead of "include", as that file's code is mandatory for the code that follows to work
    • "once" because you don't need to run that included file's code again if it has already been included (in fact it would cause an error)
      Write a Reply...