php cant find class if file name starts with a capital B -
i'm having trouble confusing error. have class , extended class. if extended file name starts capital b cannot find database class. if name else, literally else works.
my database class looks so
class database { public $db; public function __construct() { if (database == true) { $this->db = new mysqli(hostname, username, password, dbname); if ($this->db->connect_error) { exit('some of database login credentials seem wrong.' . '-' . $this->db->connect_error); } } } }
my extended class so
class blogmodel extends database { public function getblogposts() { $query = array(); if ($result = $this->db->query('select * blog')) { while ($row = $result->fetch_assoc()) { $query[] = $row; } $result->free(); } return $query; $mysqli->close(); } }
the filename blogmodel.php causes error.
fatal error: class 'database' not found in c:\wamp\www\website\app\model\blogmodel.php on line 4
if change blogmodel.php works. don't mind changing filename in interest of understanding , learning i'd know why happening.
edit: how include files
define('root', str_replace('\\', '/', $_server['document_root'])); define('host', $_server['http_host']); define('url', $_server['request_uri']); define('app', root . '/app/'); define('model', root . '/app/model/'); define('view', app . '/view/'); define('controller', root . '/app/controller/'); $models = array_diff(scandir(model), array('.', '..')); foreach ($models $m) { require_once model . $m; }
to use autoloader psr compliant need restructure directory tree.
the code use (not fully) psr-4 compliant code:
<?php #cn class name #fn file name #ns namespace #np namespace pointer class loader{ public function load($class){ $cn = ltrim($class, '\\'); $fn = ''; $ns = ''; if($np = strrpos($cn, '\\')){ $ns = substr($cn, 0, $np); $cn = substr($cn, $np + 1); $fn = str_replace('\\', directory_separator, $ns) . directory_separator; } require ($fn .= strtolower(str_replace('_', directory_separator, $cn)) . '.php'); } public function __construct(){ spl_autoload_register([$this, 'load']); } } new loader; ?>
it load files in lower case filename, if not use namespaces attempt load document root if object not exist.
if using namespaces, aka:
$var = new \path\to\object();
it attempt load object.php
webroot\path\to\
how 1 use simple, include file , next time create object keep namespace valid path.
Comments
Post a Comment