PHP MVC Loading a file. :c

Status
Not open for further replies.

GarettM

Posting Freak
Aug 5, 2010
833
136
I am trying to require a file, the script needs to require and then return a new instance (think that's the word) of that file. Simply i need to combine a namespace and a string. :)
--- EDIT ABOVE ---
Hey everyone i am trying to load my models like this:
PHP:
public function loadModel($model)
{
    require_once( dirname(__FILE__) . '/../models/' . ($model) . '.php');
    $class = "Models\\$model";
  
    return new $class($this->database);
}

But when i use
PHP:
$Test->loadModel('Test');
i get this error:
Code:
Fatal error: Cannot redeclare class Models\Test in C:\DevServer\data\localweb\app\models\Test.php on line 16

Here is the Test Class:
PHP:
<?php
    /**
     * Test Model.
     *
     * @package GarettMcCarty
     * @author  DrPepper23
     * @link    https://github.com/GarettMcCarty
     */
  
    namespace Models;
    use Exception;
  
    if(class_exists('Test') != true)
    {
        class Test
        {
            protected $database    = null;
          
          
            public function __construct($connection = null)
            {
                try {
                    $this->database        = $connection;
                } catch(Exception $e) {
                    printf('Shit: %s', $e->getMessage());
                    exit;
                }
            }
        }
    }
?>
 
Last edited:

GarettM

Posting Freak
Aug 5, 2010
833
136
Use require_once instead of include.
I tried require_once, include_once, require and include all give the same error.

This is how i solve it, added a slash b4 the namespace name.
PHP:
public function loadModel($model)
{
   $class = "\Models\\$model";
   if(class_exists($model) != true)
   {
      require_once( dirname(__FILE__) . '/../models/' . ($model) . '.php');
      return new $class($this->database);
   }
}
Please close.
 
Last edited:
Status
Not open for further replies.

Users who are viewing this thread

Top