In my root folder I have a file folder that has my common files I use between different projects. /files I have a file redis.php that has Redis class that I want to use in one of my project in /var/www/html/project/example.php The Class Redis is in /file/library/storage/redis/redis.php
my redis.php has
<?php
namespace file\library\storageedis;
class Redis{
public function init(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
}
}
?>
and in my example.php I call that namespace like
$redis = new \file\library\storageedis\Redis();
$redis->init();
but it gives me an error
[Mon May 27 12:25:48 2013] [error] [client 127.0.0.1] PHP Fatal error: Class 'file\\library\\storage\edis\\Redis' not found
Any help will be appreciated
What you are looking for is an autoloader that can map your namespaces to actual paths and include the class files before you're creating an instance of them. Take a look at the commonly used PSR-0 autoloader.
<?php
function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoload');
If you include this code in /var/www/html/project/example.php
, what happens then when you try to make an instance
$redis = new \file\library\storageedis\Redis();
Is that it will try to include this file first
/var/www/html/project/file/library/storage/redis/Redis.php
You should include the file that contains the class. You can do it manually using: require_once 'redis.php' OR create a rontina autoload as stated in the first answer