1

From the php documentation,we access global classes like

<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?> 

However,i am a lost when the doc says that

<?php
$a = new \stdClass;
?>

is functionally equivalent to:

<?php
$a = new stdClass;
?>

here http://php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.shouldicare

Can someone kindly explain what the doc is saying here.

Thanks.

1
  • 2
    They are only equivalent, if you do not use namespaces yourself. (Because then, everything is declared in the global namespace `\`) Commented Jan 26, 2013 at 14:51

2 Answers 2

3

Right above those two code examples in the docs is the important heading:

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

So the implication here is not that you can write new stdClass; inside a namespace and have it be equivalent, but rather that if you are not using namespaces at all, then you needn't worry about the backslash new \stdClass;

When working in a namespace, the rule does apply and you will need to use new \stdClass;.

And this doesn't just apply to the generic stdClass, but to any class.

// Without namespaces:
$mysqli = new MySQLi(...);

// With namespaces
$mysqli = new \MySQLi(...);
Sign up to request clarification or add additional context in comments.

Comments

2

The documentation says that \stdClass is functionally equivalent to stdClass only in:

as-yet-to-be-written code that does not contain namespaces

I.e. if you are using namespaces - as your code indicates - you will have you define the class within the current namespace (to use new stdClass); or you will just have to use the native class which does not require one (new \stdClass).

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.