开发者

PHP Name spacing problem with extends

I have a file that declares a namespace in the beginning, then does an include of two supporting files that defines classes like X, Y, etc.

Now in the main file, after declaring the namespace, I can no longer create classes that extend X. I have not declared a namespace in X or Y, I assumed the definition开发者_如何学Python at the top of the main file, before the includes, would take care of that? Shouldn't the class just default resolve to my namespace\X?

For example, in my PHP file I do this in the beginning:

namespace SGOAuth;
include 'OAuth.php';
include 'CURL.php';

And later a class I define in this file tries:

class MyClass extends CURL {...}

But I get the error: SGOAuth\CURL not found

Thanks!


Unless the CURL class is declared in the namespace SGOAuth, of course it won't exist in the namespace SGOAuth. Just including a file doesn't mean it's part of the namespace the file that includes the file is in (now that's a sentence ;)). That would make namespaces pointless.

CURL.php

// no namespace declaration, defaults to global namespace
class CURL { }

foo.php

// namespace declaration, all code *in this file* is in namespace Foo
namespace Foo;

// includes the CURL class, which is in the global namespace
include 'CURL.php';

new CURL;  // error, class does not exist in this namespace
new \CURL; // works

So class CURL by default is in the global namespace. To extend it, you need to extends \CURL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜