1

I'm trying to set up a simple example in order to understand how the ClassLoader Component of Symfony and the new PSR-0 standard work.

First I created Bar.php:

namespace Acme;

class Bar 
{
    // Implementation
    public static function helloWorld() {
        echo "Hello world!";
    }
}

Then I created a autoloader.php (under the vendor path I have the ClassLoader component):

require_once __DIR__.'/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php';

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->register();

$loader->registerNamespace('Acme', __DIR__);

Lastly I created Foo.php:

require_once 'autoloader.php';

use Acme;

class Foo extends Bar
{
    // Implementation
}

$foo = new Foo();
$foo::helloWorld();

But when I execute:

$ php Foo.php

I get the following error message:

PHP Warning: The use statement with non-compound name 'Acme' has no effect in Foo.php on line 4

PHP Fatal error: Class 'Bar' not found in Foo.php on line 7

What am I doing wrong here?

UPDATE:

If instead of using namespace Acme I use namespace Acme\Bar in Bar.php, I get the same error message as shown above.

1

2 Answers 2

1

I've found what was going on wrong. The problem was that the UniversalClassLoader class that follows the standard PSR-0, requires that the files with the namespaces cannot be in the root directory, and must be created under a minimum of one directory.

Here is the code in case someone wants to try the example.

autoloader.php

require_once __DIR__.'/vendor/Symfony/Component/ClassLoader/UniversalClassLoader.php';
$loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->registerNamespaces(array('Acme' => __DIR__ . '/src'));
$loader->register();

./src/Acme/Bar.php

namespace Acme;

class Bar 
{
    // Implementation
    public static function helloWorld() {
        echo "Hello world!";
    }
}

./src/Acme/Foo.php

namespace Acme;

require_once '../../autoloader.php';

use Acme\Bar;

class Foo extends Bar
{
    // Implementation
}

$foo = new Foo();
$foo::helloWorld();
Sign up to request clarification or add additional context in comments.

Comments

0

You can't use an entire namespace, you have tu use Acme\Bar.

1 Comment

If I use Acme\Bar as namespace in Bar.php I get the same error, I'll update the question in order to explain this.

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.