Erich Mosier
Erich Mosier

Reputation: 33

PHP how to stop class from inheriting namespace of parent class

I am trying to write an autoloader function but running into an issue. When I call my DBConnect class from inside my Product class it is inheriting the Product class namespace.

I cannot figure out how to use a "use" statement when autoloading the DBConnect class. If I try to add a "use" statement after the include in my loader function, it throws an error. So I keep getting a "Fatal error: Class 'App\Model\Entity\DbConnect' not found". It should be using "App\Config\DBConnect".

It is my first autoloader I've built so I am not sure where I am going wrong.

Thanks in advance.

bootstrap.php

require_once('Autoloader.php');
require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';
spl_autoload_register('Core\Autoloader::loader');

Autoloader.php

namespace Core;
class Autoloader
{
  public static function loader( $class, $dir = null ) {

    if ( is_null( $dir ) )
        $direct  = array(
        '/Controller',
        '/Model/Entity',
        '/Model/Table',
        '/Config'
        );

    foreach ($direct as $dir){

        $scan = scandir(ROOTPATH . $dir);
        $classname = substr(strrchr($class, "\\"), 1);
        $classfile = $classname . '.php';

        foreach($scan as $file)
        {
            if(file_exists(ROOTPATH . $dir . '/' . $classfile)){
                include ROOTPATH . $dir . '/' . $classfile;
                goto xspot;
            }
        }
    }
    xspot:
  }
}

Product.php

namespace App\Model\Entity;
require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';
include ROOTPATH . '/Core/bootstrap.php';

class Product
 {
    public function __construct($conntype = 'MYSQLI') {
        $db = new DbConnect();
        $this->conn = $db->connect($conntype);
    }

DBConnect.php

namespace App\Config;
class DbConnect {
    function connect() {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';   
        $conn = new \mysqli(DB_SERVER_MYSQLI, DB_USERNAME, DB_PASSWORD, DB_NAME, DB_PORT);
          if (mysqli_connect_errno()) {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
 }

Upvotes: 1

Views: 107

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

At first, remove line require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php'; from Product.php file as it already included in bootstrap.php
Secondly, add alias for DbConnect class as shown below:

Product.php:

namespace App\Model\Entity;

include ROOTPATH . '/Core/bootstrap.php';
use App\Config\DbConnect as DbConnect;

...
$db = new DbConnect();
...

Upvotes: 1

rafwlaz
rafwlaz

Reputation: 484

Add on top of

Product.php

use App\Config;

or use:

$db = new App\Config\DbConnect();

because now object creation use bad namespace

Upvotes: 0

Related Questions