I am trying to use PHP's traits feature and namespacing to organize my project's codes and files.
But I do not know why I get this
Fatal error: Class 'ModernPHP\News' not found in E:\www\modernphp\test.php on line 11.
There are my files in the same directory. I just have a directory modernphp; the three files are beyond this directory.
Am I misusing namespaces? Or is it something else?
<?php
namespace ModernPHP;
trait db_connect
{
protected $host;
protected $user;
protected $pwd;
protected $db;
protected $connect;
public function __construct($host, $user, $pwd, $db)
{
$this->host = $host;
$this->user = $user;
$this->pwd = $pwd;
$this->db = $db;
}
public function connect()
{
$this->connect = mysqli_connect($this->host, $this->user, $this->pwd);
mysqli_select_db($this->connect, $this->db);
}
public function query($table, $arr_fields = array(), $order_by = false)
{
$sql = 'SElECT * FROM {$table}';
return mysqli_query($this->connect, $sql);
}
}
<?php
namespace ModernPHP\News;
class News
{
use mysql;
/*
public function __construct()
{
//$db = new m
}
*/
public function latestNews()
{
}
}
<?php
namespace ModernPHP;
use ModernPHP\News;
class test {
public function __construct()
{
$news_object = new News('localhost', 'root', '', 'invo');
print_r($news_object);
}
}
$test = new Test;
--- Add at Jan.06.2016 ---
class ComposerAutoloaderInita3585bdd4dd862cdaf5a9a8f6faaa488
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInita3585bdd4dd862cdaf5a9a8f6faaa488', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
You defined your class News
in namespace ModernPHP\News
(see top line of News.php). That means the class, with namespace, is ModernPHP\News\News
, not ModernPHP\News
.
You either meant to define News
in namespace ModernPHP
(replace the namespace
line in News.php with namespace ModernPHP;
) or you need to use ModernPHP\News\News;
in your definition of ModernPHP
.
Also, you need an autoloader or explicit include
/require
statements to load your class and trait files. You can't simply do new News(...)
if you haven't loaded the News.php file or told PHP how to do so.
make sure you also have the subfolders for your namespaces e.g.
namespace ModernPHP\News;
you need a folder ModernPHP with a subfolder News, in this subfolder is your class News. You can then use the class with:
use ModernPHP\News\News;