0

Can anyone explain why the below code causes a "Cannot find class" error? Instantiating the class with the fully qualified name works, but eliminates the advantage of the "use" statement.

<?php

namespace
{
    use Foo\Bar;

    new Bar;    // Works

    $class = 'Foo\Bar'; 

    new $class; // Works

    $class = 'Bar';

    new $class; // "Cannot find class" error
}

namespace Foo
{
    class Bar {}
}

Thanks

1
  • Tested on both PHP 5.3.2 and 5.3.10 Commented Sep 19, 2012 at 16:17

1 Answer 1

2

Well, I suppose it's actually a feature. And aliases won't help here, for the same reasons:

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names. [...]

<?php 
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another'; 
$obj = new $a;      // instantiates object of class Another 
?>

And yes, it sorts of defeats the purpose of use with dynamic classes.

Sign up to request clarification or add additional context in comments.

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.