0

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\storage\redis;

    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\storage\redis\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\\redis\\Redis' not found

Any help will be appreciated

1
  • and do you have an autoloader for this? I don't think its going to work without a proper autoloader that tells php where to look for your files. Commented May 27, 2013 at 19:37

2 Answers 2

2

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\storage\redis\Redis(); 

Is that it will try to include this file first

/var/www/html/project/file/library/storage/redis/Redis.php
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.