duanmao1919 2013-01-26 14:46
浏览 60
已采纳

php命名空间,访问全局类

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.

  • 写回答

2条回答 默认 最新

  • dongzhi6146 2013-01-26 14:51
    关注

    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(...);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM