I am brand-spanking-new to the namespace concept in php.
The situation: Multiple files in a folder and they all require/include one another for their own purposes.
If i were to place them all in the same namespace, would it still be necessary to have them require/include each other?
I did think of replacing the require/include with "use", but it seems odd to have a file in namespace foo\bar to actually 'use' foo\bar... o_O
PS: I am covering all my bases by asking questions while also searching the net for answers; so if you have any good sources for info/tutorials etc please feel free to share. :D
Thank you, David
It can get messy with all the includes/requires. The included files on one included file, will be also included on the first one as well, with out explicitly calling it. I would suggest, if you are using OOP approach, start out using the __autoload()
magic method. This will save you tons of headaches down the road when you include a file on a page that's already been included elsewhere running on that page and you get a 500 server error because of it.
Yes, you have to require them, or you can use a psr-0 compatible autoloader
If i were to place them all in the same namespace, would it still be necessary to have them require/include each other?
You can create a loader class for example (it's what I always do, so you only have to include/require them once, and you only have to include/require the loader class in your controller). Here is the current one I'm using:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//include alle classes
include("classes/db.class.php");
include("classes/gastenboek.class.php");
include("classes/gebruiker.class.php");
include("classes/bericht.class.php");
session_start();
$db = new Db();
//require smarty (smarty template engine)
require('plugins/smarty/Smarty.class.php');
$smarty = new Smarty;
$smarty->setCompileDir('smarty_compile');
$smarty->setTemplateDir('templates');
//func to dump var
function dump($var)
{
//echo ##
echo '<pre>##';
//print var
print_r($var);
//echo ##
echo '##</pre>';
}
With db.class being this for example:
<?php
class Db
{
//Loading Db
public function __construct()
{
//do connect()
$this->connect();
}
//connecting and selecting db
private function connect()
{
$connection = mysql_connect('localhost', 'user', 'pw');
if(!$connection)
{
die("Kan geen verbinding maken: " . mysql_error());
}
mysql_select_db("db", $connection);
}
public function DBH()
{
try
{
$DBH = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pw');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $except)
{
echo $except->getMessage();
}
}
index.php would then only need this:
include("includes/loader.php");