简体   繁体   中英

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 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM